从zip文件中读取带有特殊字符的文件

时间:2014-01-13 15:54:53

标签: java stream zip

我的代码从zipfile读取文件,除了具有特殊字符的文件外,它工作正常。有问题的人物是'è'(见我的代码fère_champenoise)

String works="(3/(3)_juno.jpa";
     String sdoesntwork="ba/battle of fère_champenoise.jpa";

    ZipFile file1 = null;
    try {
      file1 = new ZipFile(sZipFileOld);
    } catch (IOException e) {
      System.out.println("Could not open zip file " + sZipFileOld + ": " + e);

    }

    try {
        file1.getInputStream(file1.getEntry(sdoesntwork));
    } catch (IOException e) {

        System.out.println(sdoesntwork + ": IO Error " + e);
        e.printStackTrace();
    }

它会抛出错误但不会通过异常处理程序:

Exception in thread "main" java.lang.NullPointerException
    at java.util.zip.ZipFile.getInputStream(Unknown Source)
    at ZipCompare.main(ZipCompare.java:56)

任何解决方案?

5 个答案:

答案 0 :(得分:1)

构造zipfile时,明确指定编码:file1 = new ZipFile(sZipFileOld, Charset.forName("IBM437"));

Zip文件不使用特殊字符的默认UTF-8编码

答案 1 :(得分:0)

我相信你需要指定一个编码,UTF-8。像这样:

 final InputStream in = new InputStreamReader(file1.getInputStream(file1.getEntry(sdoesntwork)), "utf-8");

确保你记得在最终结束时关闭它。

答案 2 :(得分:0)

问题是file1.getEntry(sdoesntwork)返回null,因为它找不到该条目。 如果您确定此名称是正确的,请尝试使用:

file1 = new ZipFile(sZipFileOld,StandardCharsets.UTF_8);

答案 3 :(得分:0)

它没有通过你的异常处理程序,因为是另一种类型的异常,因为找不到该条目而抛出Null指针异常。您应该检查文件定义的Charset的方式或位置。

答案 4 :(得分:0)

file1 = new ZipFile(sZipFileOld,StandardCharsets.UTF_8);

字符集-用于解码ZIP条目名称和注释的字符集(如果已设置ZIP条目的通用位标志的语言编码位,则忽略该字符集。)

如果zip条目及其注释为ASCII,则不必使用这种方式来构造ZipFile。

相关问题