JDK 內建 java.util.zip 對中文文件名支援不佳,實務上常改用 Apache Ant 提供的 org.apache.tools.zip 套件,可指定編碼(如 GBK、UTF-8)正確讀取條目名稱。
<dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.10.14</version> </dependency>
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.*;
import java.util.Enumeration;
public class UnZipFiles {
public static void main(String[] args) {
String zipPath = "D:/test.zip";
String destDir = "F:/unZipFiles/";
File zipFile = new File(zipPath);
try (ZipFile zf = new ZipFile(zipFile, "GBK")) { // 指定編碼
Enumeration entries = zf.getEntries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File outFile = new File(destDir, entry.getName());
if (entry.isDirectory()) {
outFile.mkdirs();
} else {
outFile.getParentFile().mkdirs();
try (InputStream is = zf.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(outFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
}
}
}
System.out.println("解壓完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
new ZipFile(file, "GBK") 解決 Windows 建立的 ZIP 中文亂碼;Linux 環境常用 UTF-8。mkdirs();為文件時需先建立父目錄再寫入。ZipException: Invalid header — 確認文件確為 ZIP 格式,非 RAR/7z。BufferedInputStream 包裝輸入流。