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

Java 原生 ZIP 壓縮與解壓縮工具類:ZipUtil 完整實作

     編輯:Java 相關知識

前言

Java java.util.zip 套件提供 ZIP 壓縮/解壓縮核心功能。本文整理兩個可直接使用的工具類別:ZipUtil(支援目錄遞迴、Checksum 驗證)與 ZipToFile(簡易單檔解壓),並說明關鍵參數與例外處理。

ZipUtil 核心功能

  • zip(sourceDir, zipFileDir):將目錄壓縮為同名 .zip,使用 Adler32 校驗碼。
  • unzip(zipFile, destDir):解壓縮至指定目錄,自動建立子目錄。
  • 緩衝區大小 10KB,遞迴處理子目錄。

關鍵程式碼片段

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

ZipToFile 簡易解壓範例

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 名稱可能包含相對路徑(../),需做路徑遍歷防護。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved