我有一个包含以下内容的zip文件:
Temperature_°C.log 中的内容:单位°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
时,它显示为垃圾字符。
我应该如何解决呢?
答案 0 :(得分: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);
}
}