1 /**
2 * 多个文件压缩
3 * @param srcFiles 压缩前的文件
4 * @param zipFile 压缩后的文件
5 */
6 public static void zipFiles(File[] srcFiles, File zipFile) {
7 // 判断压缩后的文件存在不,不存在则创建
8 if (!zipFile.exists()) {
9 try {
10 zipFile.createNewFile();
11 } catch (IOException e) {
12 e.printStackTrace();
13 }
14 }
15 // 创建 FileOutputStream 对象
16 FileOutputStream fileOutputStream = null;
17 // 创建 ZipOutputStream
18 ZipOutputStream zipOutputStream = null;
19 // 创建 FileInputStream 对象
20 FileInputStream fileInputStream = null;
21
22 try {
23 // 实例化 FileOutputStream 对象
24 fileOutputStream = new FileOutputStream(zipFile);
25 // 实例化 ZipOutputStream 对象
26 zipOutputStream = new ZipOutputStream(fileOutputStream);
27 // 创建 ZipEntry 对象
28 ZipEntry zipEntry = null;
29 // 遍历源文件数组
30 for (int i = 0; i < srcFiles.length; i++) {
31 // 将源文件数组中的当前文件读入 FileInputStream 流中
32 fileInputStream = new FileInputStream(srcFiles[i]);
33 // 实例化 ZipEntry 对象,源文件数组中的当前文件
34 zipEntry = new ZipEntry(srcFiles[i].getName());
35 zipOutputStream.putNextEntry(zipEntry);
36 // 该变量记录每次真正读的字节个数
37 int len;
38 // 定义每次读取的字节数组
39 byte[] buffer = new byte[1024];
40 while ((len = fileInputStream.read(buffer)) > 0) {
41 zipOutputStream.write(buffer, 0, len);
42 }
43 fileInputStream.close();
44 }
45 zipOutputStream.closeEntry();
46 zipOutputStream.close();
47 fileOutputStream.close();
48 } catch (IOException e) {
49 e.printStackTrace();
50 }finally{
51 //压缩完成删除压缩前的文件
52 for (File file : srcFiles) {
53 if(file.exists()){
54 file.delete();
55 }
56 }
57 }
58 }