Java NIO ZipFileSystem:创建文件系统时“找不到 zip END 标头”

新手上路,请多包涵

我在这里问这个是因为谷歌搜索这个错误只会让我在写一个 zip 文件时点击,而我只是想阅读它。

我有一个单元测试,我正在尝试测试以下生产代码:

 Map<String, String> zipProps = new HashMap<>();
URI zipUri = URI.create("jar:file:" + itemZipPath.toString());
try (FileSystem zipfiles = FileSystems.newFileSystem(zipUri, zipProps)) {
   // do stuff...
} catch (IOException e) {
   // log an error
}

然而,这在包含尝试的行上失败了:

 java.util.zip.ZipError: zip END header not found
at com.sun.nio.zipfs.ZipFileSystem.zerror(ZipFileSystem.java:1605)
at com.sun.nio.zipfs.ZipFileSystem.findEND(ZipFileSystem.java:1021)
at com.sun.nio.zipfs.ZipFileSystem.initCEN(ZipFileSystem.java:1030)
at com.sun.nio.zipfs.ZipFileSystem.<init>(ZipFileSystem.java:130)
at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:117)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:276)
at com.company.PageCommandHandler$ProvisioningSteps.getItemModel(PageCommandHandler.java:105)

我尝试使用 OSX 的 zip 实用程序和使用 jar cvf 创建 zipfile,但都失败了( file <filename> 的输出略有不同)。我能找到的有关此错误的所有信息都与使用 Java NIO 创建 zip 文件有关,但如您所见,我只是在进行读取(目前验证 ZIP 中是否存在某个文件)。对这里出了什么问题有什么想法吗?

原文由 Ton van Bart 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 928
1 个回答

我遇到了完全相同的错误。 Java 8。原因是,我错误地创建了一个空文件,而不仅仅是对象:

 File zipFile = new File(path);
zipFile.createNewFile();

然后将这条路径传递给

URI uri = URI.create("jar:file:" + zipFile.getAbsolutePath());

为了修复它,我没有创建文件本身,只创建了一个 File 对象:

 File zipFile = new File(path);
URI uri = URI.create("jar:file:" + zipFile.getAbsolutePath());

为了使它更可靠,我建议先删除文件(如果存在):

 File zipFile = new File(path);
//Caused by: java.util.zip.ZipError: zip END header not found
if (zipFile.exists()){
    try {
        Files.delete(Paths.get(zipFile.getAbsolutePath()));
    } catch (IOException e) {
        throw new IllegalStateException(
                "Could not delete file.", e);
    }
}
...
URI uri = URI.create("jar:file:" + zipFile.getAbsolutePath());

可能在某些情况下,删除文件的解决方案是不可接受的。例如,如果您向同一个 zip 文件添加多个条目。但在我的用例中没问题。

原文由 Alexandr 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题