java.util.zip 預設使用 UTF-8 編碼檔名,但舊版 Windows 解壓工具 (WinRAR、資源管理器) 預期 GBK/CP936,導致中文亂碼。file.encoding 不符,造成字串在進入 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();
}
}
}
| 方法 | 說明 |
|---|---|
setEncoding(String) | 設定檔名、註解編碼 (支援 GBK、UTF-8、CP936 等) |
setComment(String) | 設定壓縮包註解 |
setMethod(int) | DEFLATED 壓縮 / STORED 僅存儲 |
setLevel(int) | 壓縮等級 0-9 (預設 6) |
setUseUnicodeExtraFields(true),現代解壓工具 (7-Zip、Win10 探索器) 可正確顯示 UTF-8 檔名,同時保留 GBK 落地兼容。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。