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

Java 壓縮 ZIP 完整解決方案:支援中文檔名 (Apache Ant ZipOutputStream)

     編輯:J2SE

問題

JDK 內建 java.util.zip 不支援中文檔名,壓縮含中文路徑會報錯或產生亂碼。

解決方案:Apache Ant 的 zip 實現

  • Maven 依賴: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 路徑以 / 分隔,目錄以 / 結尾。
  • Ant 版 ZipOutputStream 預設使用 UTF-8 編碼檔名,完美支援中文。

遺憾

JDK 與 Ant 的 zip 實現均無法解壓 RAR 格式。Java 純實現解壓 RAR 需第三方庫 (如 junrar),但授權限制較多,建議呼叫系統 unrar 命令或使用 7-Zip JBinding。

本文來自編程入門網:原文連結

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved