Maven 依賴
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.12</version>
</dependency>
格式對比
| 格式 | 特點 | 適用場景 |
| zip | 多文件、目錄結構、跨平台 | 通用打包分發 |
| gzip | 單文件、高壓縮比、配合 tar | Linux 日誌、傳輸 |
| 7z | 最高壓縮比、支持大文件 | 備份、存檔 |
| zlib | 數據流壓縮、無文件頭 | 網絡傳輸、內存壓縮 |
核心工具類
public class CompressUtils {
// zip 多文件
public static void zip(String inputPaths, String output, String entryName) throws Exception {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output))) {
for (String path : inputPaths.split("\\|")) {
try (FileInputStream in = new FileInputStream(path)) {
out.putNextEntry(new ZipEntry(entryName != null ? entryName : new File(path).getName()));
copy(in, out);
out.closeEntry();
}
}
}
}
// gzip 單文件
public static void gzip(String input, String output, String entryName) throws Exception {
try (GzipCompressorOutputStream out = new GzipCompressorOutputStream(
new FileOutputStream(output), new GzipParameters().setFilename(entryName));
FileInputStream in = new FileInputStream(input)) {
copy(in, out);
}
}
// 7z 多文件
public static void sevenZ(String inputPaths, String output, String entryName) throws Exception {
try (SevenZOutputFile out = new SevenZOutputFile(new File(output))) {
for (String path : inputPaths.split("\\|")) {
SevenZArchiveEntry entry = out.createArchiveEntry(new File(path),
entryName != null ? entryName : new File(path).getName());
out.putArchiveEntry(entry);
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(path))) {
copy(in, out);
}
out.closeArchiveEntry();
}
}
}
// zlib 數據流
public static void zlib(String input, String output) throws Exception {
try (DeflateCompressorOutputStream out = new DeflateCompressorOutputStream(
new FileOutputStream(output), new DeflateParameters().setWithZlibHeader(true));
FileInputStream in = new FileInputStream(input)) {
copy(in, out);
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
}
}
選型建議
- 需目錄結構、跨平台解壓 → zip
- 單文件最大壓縮 → gzip / 7z
- 網絡流/內存數據壓縮 → zlib