我正在使用 zip4j 解压缩文件,但文件名字符集有问题。 这是我的代码,
try {
ZipFile zipFile = new ZipFile(source);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
System.out.println(System.getProperty("file.encoding"));
zipFile.setFileNameCharset("UTF-8");
zipFile.extractAll(destination);
} catch (ZipException e) {
System.out.println(e.getMessage());
}
}
工作正常,但文件名是这样的
最佳答案
如果您想解压由其他软件创建的 zip 文件。 文件名的字符集可能是系统默认的字符集(如GBK、Shift-JIS或其他字符集...)
在这种情况下,如果源文件名之一包含该字符集中不存在的 unicode 字符。 该 ZipEntry 中的文件名被转换为 UTF-8。
要解压这种zip文件,必须通过自定义代码将文件名一一转换。
ZipFile zipFile = new ZipFile("input.zip");
UnzipParameters param = new UnzipParameters();
zipFile.setFileNameCharset("ISO8859-1");
List list = zipFile.getFileHeaders();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
FileHeader fh = (FileHeader) iterator.next();
byte[] b = fh.getFileName().getBytes("ISO8859-1");
String fname = null;
try {
fname = new String(b, "UTF-8");
if (fname.getBytes("UTF-8").length != b.length) {
fname = new String(b,"GBK");//most possible charset
}
} catch (Throwable e) {
//try other charset or ...
System.err.println("Invalid file name: "+fname);
}
z.extractFile(fh, dir, param, fname);
}
关于java - zip4j setFileNameCharset 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132515/