
zipinputstream 指定字符集
问题:
使用 zipinputstream 解压文件时,指定字符集后,解压中文文件或文件夹仍会报错。
回答:
对于使用 utf-8 编码的压缩包,请将字符集指定为 gbk,代码如下:
fileinputstream input = new fileinputstream(targetpath);
zipinputstream zipinputstream = new zipinputstream(new bufferedinputstream(input), charset.forname("gbk"));原因是不同操作系统平台使用不同的 zip 压缩包编码格式。windows 默认使用 gb2312,而 mac 和 linux 默认使用 utf-8。若指定 utf-8,则无法正确转换 gb2312 字符,导致解压失败。
兼容不同平台:
为了在不同平台上可靠地处理 zip 压缩包,可以使用 apache commons compress 包提供的压缩/解压缩方法:
org.apache.commons commons-compress 1.21
使用方法:
ZipFile zipFile = new ZipFile(targetPath);
for (ZipArchiveEntry entry : zipFile.getEntries()) {
InputStream inputStream = zipFile.getInputStream(entry);
... // 处理输入流
}










