3

我想打开一个没有 java.util.zip.ZipFile 条目的 ZIP 文件。但在构造函数上,我得到以下异常:'java.util.zip.ZipException:打开 zip 文件时出错'。如何打开空的 ZIP?

该 ZIP 文件是由 linux 下的命令行 zip 程序创建的。我只是从一个 ZIP 文件中删除了所有条目。

我需要这个作为我写的课程的测试数据。对于这种情况,该类应该只返回一个空列表,但损坏的 ZIP 文件应该返回一个错误。

有关该问题的更多解释。我有一个接口,用于从不同来源提取一些文档。其他实现从 web 服务或目录中收集它们,这个实现来自 ZIP 文件。该接口为 Iterator 提供了更多功能。所以我想决定 ZIP 文件是空的还是损坏的。

4

7 回答 7

5

hack:您可以假设所有空 ZIP 都是相同的,只需对其长度/校验和进行硬编码以进行验证。

于 2008-12-14T16:24:26.410 回答
2

不知道为什么要这样实现,但是为什么需要成功打开一个空的Zip文件呢?无论如何,您都无法使用 java.util.zip.ZipFile 对其进行修改...

因此,您可以捕获 ZipException(对于无效格式的 zip 文件会抛出该异常),如果您捕获它,则跳过该文件。

于 2008-12-12T15:16:43.180 回答
2

我现在对这个问题的解决方案是,我只是使用 ZipInputStream 而不是 ZipFile。此类适用于空 ZIP 文件。我不知道原因,为什么一个有效而另一个无效。

于 2008-12-15T14:51:40.980 回答
1

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.

于 2010-01-05T00:45:49.550 回答
0

你确定它是一个有效的 zip 文件吗?那将是我的第一个猜测。

于 2008-12-12T15:19:19.510 回答
0

ZIP 文件格式有错误检查这里的 JDK

于 2008-12-12T15:29:20.597 回答
-1

使用ZipOutputStream.

于 2008-12-14T16:14:55.710 回答