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

Java 解決 Zip 壓縮中文亂碼:Apache Ant ZipOutputStream 實戰

     編輯:Java 程式設計入門

亂碼根因

  1. 檔名/註解編碼:JDK 內建 java.util.zip 預設使用 UTF-8 編碼檔名,但舊版 Windows 解壓工具 (WinRAR、資源管理器) 預期 GBK/CP936,導致中文亂碼。
  2. 專案編碼不一致:原始碼檔案編碼 (GBK/UTF-8) 與運行時 file.encoding 不符,造成字串在進入 Zip 前已錯誤。

解決方案:Apache Ant Zip 類庫

Maven 依賴:

<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.14</version>
</dependency>

核心代碼

import org.apache.tools.zip.ZipOutputStream;
import org.apache.tools.zip.ZipEntry;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class ZipEncodingDemo {
    public static void main(String[] args) throws IOException {
        File src = new File("中文測試.txt");
        File zip = new File("output.zip");

        try (ZipOutputStream zos = new ZipOutputStream(
                new BufferedOutputStream(new FileOutputStream(zip)))) {

            // 關鍵:設定編碼為 GBK (兼容 Windows 內建解壓)
            zos.setEncoding("GBK");

            // 檔名編碼
            ZipEntry entry = new ZipEntry("中國人.txt");
            zos.putNextEntry(entry);

            // 內容寫入
            try (FileInputStream fis = new FileInputStream(src)) {
                byte[] buf = new byte[8192];
                int len;
                while ((len = fis.read(buf)) > 0) zos.write(buf, 0, len);
            }
            zos.closeEntry();

            // 註解編碼 (同樣受 setEncoding 控制)
            zos.setComment("中文測試註解");
            zos.finish();
        }
    }
}

關鍵 API

方法說明
setEncoding(String)設定檔名、註解編碼 (支援 GBK、UTF-8、CP936 等)
setComment(String)設定壓縮包註解
setMethod(int)DEFLATED 壓縮 / STORED 僅存儲
setLevel(int)壓縮等級 0-9 (預設 6)

進階:跨平台兼容策略

  • 純 ASCII 檔名:避免編碼問題,但用戶體驗差。
  • 雙版本:生成兩個 Zip (GBK 給 Windows、UTF-8 給 Linux/Mac),安裝程式根據平台選擇。
  • Info-ZIP Unicode Path Extra Field (0x7075):Ant 1.10+ 支援 setUseUnicodeExtraFields(true),現代解壓工具 (7-Zip、Win10 探索器) 可正確顯示 UTF-8 檔名,同時保留 GBK 落地兼容。

JDK 內建替代 (Java 7+)

try (FileSystem fs = FileSystems.newFileSystem(Paths.get("out.zip"),
        Map.of("create", "true", "encoding", "GBK"))) {
    Files.copy(Paths.get("中文.txt"), fs.getPath("中文.txt"));
}

但 java.util.zip 仍無法正確處理註解編碼,生產環境建議繼續使用 Ant Zip。

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