Happyjava's blog site

Happyjava's blog site,分享编程知识,顺便发发牢骚

0%

Java Zip工具类

由于项目需要打包下载素材,所以需要用到打包压缩功能。谷歌了下没有找到自己很想要的的工具类,干脆自己研究下写一个。

ZipUtils.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package cn.happyjava.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* 压缩工具类
*
* @author Happyjava
*/
public class ZipUtils {

/**
* 压缩目录
*
* @param sourceDir 需要压缩的目录,如果目录为空则输出一个空的压缩文件
* @param targetFile 目标文件(zip)
* @param overlayFile 如果文件存在,是否覆盖
* @throws IOException exception
*/
public static void zipDir(String sourceDir, String targetFile, boolean overlayFile) throws IOException {
if (sourceDir == null || targetFile == null) {
throw new NullPointerException();
}
File dir = new File(sourceDir);
if (!dir.exists()) {
throw new IllegalArgumentException(String.format("sourceDir[%s] not exist", sourceDir));
}
if (!dir.isDirectory()) {
throw new IllegalArgumentException(String.format("sourceDir[%s] is not a directory", sourceDir));
}
if (!overlayFile && new File(targetFile).exists()) {
throw new IllegalArgumentException(String.format("targetFile[%s] is exist,zip fail", targetFile));
}
File[] files = dir.listFiles();
zip(targetFile, files);
}

/**
* 压缩文件(可以多个)
*
* @param targetFile 目标文件
* @param overlayFile 是否覆盖目标文件
* @param files 要压缩的File,如果传入null则会生成一个空的压缩文件
* @throws IOException exception
*/
public static void zipFile(String targetFile, boolean overlayFile, File... files) throws IOException {
if (targetFile == null) {
throw new NullPointerException();
}
if (!overlayFile && new File(targetFile).exists()) {
throw new IllegalArgumentException(String.format("targetFile[%s] is exist,zip fail", targetFile));
}
zip(targetFile, files);
}

private static void zip(String targetFile, File[] files) throws IOException {
if (files == null) {
files = new File[0];
}
try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
for (File file : files) {
if (!file.exists()) {
continue;
}
try (FileInputStream inputStream = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) >= 0) {
zipOutputStream.write(bytes, 0, length);
}
}

}
}
}

}