JDK 內建 java.util.zip 不支援中文檔名,壓縮含中文路徑會報錯或產生亂碼。
org.apache.ant:ant:1.10.x (或直接引用 ant.jar)。org.apache.tools.zip.ZipOutputStream、ZipEntry,API 與 JDK 版相近但內建 UTF-8 編碼支援。
import java.io.*;
import org.apache.tools.zip.ZipOutputStream;
import org.apache.tools.zip.ZipEntry;
public class CompressBook {
public void zip(String inputPath) throws Exception {
zip("c:\\test.zip", new File(inputPath));
}
private void zip(String zipPath, File input) throws Exception {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) {
zip(out, input, "");
}
}
private void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] children = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.isEmpty() ? "" : base + "/";
for (File child : children) zip(out, child, base + child.getName());
} else {
out.putNextEntry(new ZipEntry(base));
try (FileInputStream in = new FileInputStream(f)) {
byte[] buf = new byte[8192]; int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
}
}
}
}
byte[] 緩衝區讀寫,避免單位元 read()/write() 效能極差。ZipEntry 路徑以 / 分隔,目錄以 / 結尾。ZipOutputStream 預設使用 UTF-8 編碼檔名,完美支援中文。JDK 與 Ant 的 zip 實現均無法解壓 RAR 格式。Java 純實現解壓 RAR 需第三方庫 (如 junrar),但授權限制較多,建議呼叫系統 unrar 命令或使用 7-Zip JBinding。
本文來自編程入門網:原文連結