Java NIO ZipFileSystem: “zip END header not found” while creating file system

て烟熏妆下的殇ゞ 提交于 2019-12-04 13:02:23

I've met exactly the same error. Java 8. The reason was, by mistake I created an empty file, not only object:

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

An then passed this path to

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

To fix it, I did not create file itself, only created a File object:

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

To make it more reliable I would offer to delete file first if it exists:

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());

Probably in some case the solution with deletion of the file is not acceptable. For instance, if you add to the same zip file several entries. But in my use case it is OK.

Ton van Bart

I tried using the normal ZipInputStream and related classes, but kept having issues, so the problem did not seem related to NIO. A colleague of mine found this question on SO: Extracting zipped file from ResourceStream throws error "Invalid stored block lengths"

So I tried adding this snippet to my pom.xml as well:

<properties>
    <project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
</properties>

After this, all problems disappeared and all my tests turned green. I did not revert back to NIO as I was happy enough getting to a working solution, but I'm pretty sure this would solve the problem on NIO as well.

Posted here in hopes that it helps somebody having the same issue some day.

Maybe you didn't used the ZipInputStream class ? What is on line 326 ?

Here is some example for decompressing and extracting zip files. http://www.oracle.com/technetwork/articles/java/compress-1565076.html

FileInputStream fis = new FileInputStream("figs.zip"); ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));

Once a ZIP input stream is opened, you can read the zip entries using the getNextEntry method which returns a ZipEntry object. If the end-of-file is reached, getNextEntry returns null:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!