Java java.util.zip 套件提供 ZIP 壓縮/解壓縮核心功能。本文整理兩個可直接使用的工具類別:ZipUtil(支援目錄遞迴、Checksum 驗證)與 ZipToFile(簡易單檔解壓),並說明關鍵參數與例外處理。
zip(sourceDir, zipFileDir):將目錄壓縮為同名 .zip,使用 Adler32 校驗碼。unzip(zipFile, destDir):解壓縮至指定目錄,自動建立子目錄。public static boolean zip(String sourcePath, String zipDir) {
File source = new File(sourcePath);
File zipFile = new File(zipDir, source.getName() + ".zip");
try (FileOutputStream fos = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fos, new Adler32());
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(cos))) {
zos.setMethod(ZipOutputStream.DEFLATED);
compress(source, zos, source.getName());
return true;
} catch (IOException e) { return false; }
}
private static void compress(File file, ZipOutputStream out, String baseName) throws IOException {
if (file.isFile()) {
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
String entryName = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(baseName));
out.putNextEntry(new ZipEntry(entryName));
byte[] buf = new byte[BUFFER];
int len;
while ((len = bis.read(buf)) > 0) out.write(buf, 0, len);
out.closeEntry();
}
} else {
for (File f : file.listFiles()) compress(f, out, baseName);
}
}
public static boolean unzip(String zipPath, String zipName, String targetDir) {
File file = new File(zipPath, zipName);
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(file))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File outFile = new File(targetDir, entry.getName().replace('\\', '/'));
if (entry.isDirectory()) {
outFile.mkdirs();
} else {
outFile.getParentFile().mkdirs();
try (FileOutputStream fos = new FileOutputStream(outFile);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] buf = new byte[FILE_BUFFER_SIZE];
int len;
while ((len = zis.read(buf)) > 0) bos.write(buf, 0, len);
}
}
zis.closeEntry();
}
return true;
} catch (IOException e) { return false; }
}
ZipOutputStream 串流式寫入,避免記憶體溢位。source.isDirectory() 確保來源存在。ZipEntry 名稱可能包含相對路徑(../),需做路徑遍歷防護。