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 包提供的压缩/解压缩方法:
<dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-compress</artifactid> <version>1.21</version> </dependency>
使用方法:
ZipFile zipFile = new ZipFile(targetPath); for (ZipArchiveEntry entry : zipFile.getEntries()) { InputStream inputStream = zipFile.getInputStream(entry); ... // 处理输入流 }
以上就是ZipInputStream解压中文文件报错?如何解决跨平台字符集问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号