Mnementh
Mnementh

Reputation: 51311

Why I get an Exception on opening an empty ZIP-file with java.util.zip.ZipFile?

I want to open a ZIP-file, that have no entries with java.util.zip.ZipFile. But on the constructor I get the following exception: 'java.util.zip.ZipException: error in opening zip file'. How can I open the empty ZIP?

That ZIP-file is created by the commandline zip-program under linux. I simply deleted all entries from a ZIP-file.

I need this as testdata for a class I write. The class should simply return an empty list for this case, but broken ZIP-files should return an error.

For some more explanation on the problem. I have an interface, for extracting some documents from different sources. Other implementations gather them from webservices or directories, this implementation from ZIP-files. The interface give an Iterator with some more functionality. So I want to decide, if the ZIP-file is empty or broken.

Upvotes: 3

Views: 5134

Answers (7)

Jeff
Jeff

Reputation: 16031

I think the reason ZipInputStream works and ZipFile does not is because of the two different ways that zip files are read. The ZipFile constructor attempts to read the ZipFile's table of contents, which is written to the end of the file. If it can't read the TOC, it throws a ZipException (with almost no helpful info contained therein), which I think is what you're seeing. ZipInputStream, however, reads the entries out of the zip file sequentially starting at the beginning of the file, so it seems more robust in this case.

This is all very poorly documented and I've run into similar problems myself using ZipFile. Both methods of reading from a zip file are valid, but you'd think the API docs would mention the implications of the random access/TOC method of reading through constructor versus reading through a ZipInputStream.

Upvotes: 1

Mnementh
Mnementh

Reputation: 51311

My solution for this problem is now, that I simply use ZipInputStream instead of ZipFile. This class works well with empty ZIP-files. I don't know about the reason, why one works and the other not.

Upvotes: 2

Yoni Roit
Yoni Roit

Reputation: 28686

hack: you can assume that all empty ZIPs are the same and just hardcode it's length/chechsum to validate against.

Upvotes: 5

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Use a ZipOutputStream.

Upvotes: -1

yrcjaya
yrcjaya

Reputation: 413

The ZIP file format has errors check the JDK here.

Upvotes: 0

recursive
recursive

Reputation: 86074

Are you sure it is a valid zip file? That would be my first guess.

Upvotes: 0

bezmax
bezmax

Reputation: 26132

I don't know why is it implemented this way, but why do you need to succesfully open an empty Zip file? You can't modify it with java.util.zip.ZipFile anyway...

So you can just catch the ZipException (which is thrown for invalid format zip files), and skip the file if you catch it.

Upvotes: 3

Related Questions