我有一个包含以下内容的 zip 文件:
Temperature_°C.log里面的内容:unit°C
我使用以下代码打印 zip 中的所有文件名:
public static void main(String[] args) {
try {
ZipFile zipFile = new ZipFile("Test.zip", Charset.forName("UTF-8"));
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
try {
ZipEntry zipEntry = entries.nextElement();
System.out.println(zipEntry.getName());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
zipFile.close();
} catch (IOException ex) {
Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
在行:ZipEntry zipEntry = entries.nextElement();
Temperature_°C.log 它抛出 java.lang.IllegalArgumentException: MALFORMED
我试过 UTF-8
但它不工作。当我尝试使用 ISO-8859-1
时,它显示垃圾字符。
我该如何解决?
最佳答案
有同样的问题,但有西里尔字符。必须使用 commons-compress库而不是标准。
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
public static void main(String[] args) {
try(ZipFile zipFile = new ZipFile("Test.zip")) { //UTF-8 by default
Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
while (entries.hasMoreElements()) {
try {
ZipArchiveEntry zipEntry = entries.nextElement();
System.out.println(zipEntry.getName());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
关于Java : Read a file with special characters from a Zip file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64448616/