1 package com.wdxc.util;
2 import java.io.BufferedInputStream;
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.util.zip.CRC32;
7 import java.util.zip.CheckedOutputStream;
8 import java.util.zip.ZipEntry;
9 import java.util.zip.ZipOutputStream;
10
11 import org.apache.log4j.Logger;
12
13 /**
14 * zip文件压缩工具类
15 *
16 * @author : wangbo
17 */
18 public class ZipCompressor {
19 private Logger logger = Logger.getLogger(ZipCompressor.class);
20 static final int BUFFER = 8192;
21 private File zipFile;
22
23 /**
24 * 压缩文件构造函数
25 * @param pathName 压缩的文件存放目录
26 */
27 public ZipCompressor(String pathName) {
28 zipFile = new File(pathName);
29 }
30
31 /**
32 * 执行压缩操作
33 * @param srcPathName 被压缩的文件/文件夹
34 */
35 public void compressExe(String srcPathName) {
36 File file = new File(srcPathName);
37 if (!file.exists()){
38 throw new RuntimeException(srcPathName + "不存在!");
39 }
40 try {
41 FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
42 CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,new CRC32());
43 ZipOutputStream out = new ZipOutputStream(cos);
44
45 String basedir = "";
46 compressByType(file, out, basedir);
47 out.close();
48 } catch (Exception e) {
49 e.printStackTrace();
50 logger.error("执行压缩操作时发生异常:"+e);
51 throw new RuntimeException(e);
52 }
53 }
54
55 /**
56 * 判断是目录还是文件,根据类型(文件/文件夹)执行不同的压缩方法
57 * @param file
58 * @param out
59 * @param basedir
60 */
61 private void compressByType(File file, ZipOutputStream out, String basedir) {
62 /* 判断是目录还是文件 */
63 if (file.isDirectory()) {
64 logger.info("压缩:" + basedir + file.getName());
65 this.compressDirectory(file, out, basedir);
66 } else {
67 logger.info("压缩:" + basedir + file.getName());
68 this.compressFile(file, out, basedir);
69 }
70 }
71
72 /**
73 * 压缩一个目录
74 * @param dir
75 * @param out
76 * @param basedir
77 */
78 private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
79 if (!dir.exists()){
80 return;
81 }
82
83 File[] files = dir.listFiles();
84 for (int i = 0; i < files.length; i++) {
85 /* 递归 */
86 compressByType(files[i], out, basedir + dir.getName() + "/");
87 }
88 }
89
90 /**
91 * 压缩一个文件
92 * @param file
93 * @param out
94 * @param basedir
95 */
96 private void compressFile(File file, ZipOutputStream out, String basedir) {
97 if (!file.exists()) {
98 return;
99 }
100 try {
101 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
102 ZipEntry entry = new ZipEntry(basedir + file.getName());
103 out.putNextEntry(entry);
104 int count;
105 byte data[] = new byte[BUFFER];
106 while ((count = bis.read(data, 0, BUFFER)) != -1) {
107 out.write(data, 0, count);
108 }
109 bis.close();
110 } catch (Exception e) {
111 throw new RuntimeException(e);
112 }
113 }
114
115 public static void main(String[] args) {
116 ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip");
117 zc.compressExe("E:\\ftpdown");
118
119 }
120 }