JDK java.util.zip 內建支援 ZIP 與 GZIP 解壓,無需第三方庫。本文提供可直接複製執行的兩類完整範例。
public static void unzip(String zipPath, String destDir) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipPath))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File outFile = new File(destDir, entry.getName());
if (entry.isDirectory()) {
outFile.mkdirs();
} else {
outFile.getParentFile().mkdirs();
try (FileOutputStream fos = new FileOutputStream(outFile)) {
byte[] buf = new byte[8192];
int len;
while ((len = zis.read(buf)) > 0) fos.write(buf, 0, len);
}
}
zis.closeEntry();
}
}
}
public static void gunzip(String gzPath, String outPath) throws IOException {
try (GZIPInputStream gis = new GZIPInputStream(new FileInputStream(gzPath));
FileOutputStream fos = new FileOutputStream(outPath)) {
byte[] buf = new byte[8192];
int len;
while ((len = gis.read(buf)) > 0) fos.write(buf, 0, len);
}
}
// 若 .gz 內為文字日誌,可直接逐行讀取
try (BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("app.log.gz")), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) System.out.println(line);
}
ZipInputStream(Files.newInputStream(path), StandardCharsets.UTF_8) (需 JDK 11+ ZipInputStream(Path, Charset) 建構子)。舊版本需 Apache Commons Compress ZipFile 指定編碼。entry.getName() 不含 ../ 等路徑穿越字串。Zip4j 或 Commons Compress (有限支援)。