首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 解壓 ZIP / GZIP 檔案完整代碼範例 (標準庫無第三方依賴)

     編輯:Java 相關知識

JDK java.util.zip 內建支援 ZIP 與 GZIP 解壓,無需第三方庫。本文提供可直接複製執行的兩類完整範例。

1. 解壓 ZIP (多檔案、目錄結構)

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();
        }
    }
}

2. 解壓 GZIP (單檔案流,常見 .gz 日誌)

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);
}

常見坑點

  • ZIP 中文檔名亂碼:JDK 7- 使用默認編碼 (CP437);JDK 8+ 可用 ZipInputStream(Files.newInputStream(path), StandardCharsets.UTF_8) (需 JDK 11+ ZipInputStream(Path, Charset) 建構子)。舊版本需 Apache Commons Compress ZipFile 指定編碼。
  • 大檔案記憶體:採用緩衝區流式讀寫 (如上 8KB buffer),**切勿一次性 readAllBytes**。
  • 目錄遍歷攻擊:解壓前檢查 entry.getName() 不含 ../ 等路徑穿越字串。

進階需求

  • 支援 RAR / 7z / TAR → 必須引入 Apache Commons Compress (統一 API 支援 20+ 格式)。
  • 解壓密碼保護 ZIP → 標準庫不支援,需 Zip4j 或 Commons Compress (有限支援)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved