【问题标题】:Unable to read files from ZIP file input stream无法从 ZIP 文件输入流中读取文件
【发布时间】:2019-04-10 08:50:43
【问题描述】:

我有一个 Zip 文件,我正在尝试阅读。我不想使用ZipFile,因为将来我想对不是来自文件的数据执行此操作。

这是我迄今为止尝试过的。它不打印res00000.dat 的内容,而是打印一个空行。我不知道如何解决这个问题

ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
    if (!zipEntry.getName().equals("res00000.dat")) {
        zipInputStream.closeEntry();
        continue;
    }
}
int len;
ByteArrayOutputStream byteArrayOutputStream = new ByterrayOutputStream();
byte[] buffer = new byte[1024];
while ((len = zipInputStream.read(buffer)) > 0) {
    byteArrayOutputStream.write(buffer, 0, len);
}
String xml = byteArrayOutputStream.toString();
System.out.println(xml);
zipInputStream.closeEntry();
zipInputStream.close();
return null;

我的 ZIP 文件中只有两个文件。这是我正在尝试解析的 Blackboard 测试库文件:

Zip file
+-imsmanifest.xml
+-res00000.dat

有人可以帮忙吗?

【问题讨论】:

  • 在调试器下逐步运行代码并检查相关值。
  • 如果您不在 Windows 中,请尝试查看“unzip -v blackboardtest.zip”的输出,以验证 res00000.dat 条目的大小。此外,请确认 res00000.dat 位于 zip 文件的根目录中,而不是目录中。

标签: java zip unzip zipfile


【解决方案1】:

您的代码目前无法处理缺失的条目。它只是默默地滚动到ZipInputStream 的末尾,因此无法判断发生了什么。当名称标识的条目丢失时,您可以执行以下操作以获取异常:

public String readEntry(ZipInputStream in, String name) {
  while ((zipEntry = in.getNextEntry()) != null) {
    if (zipEntry.getName().equals(name)) {
      return readXml(zipInputStream);
    }
  }
  throw new IllegalStateException(name + " not found inside ZIP");
}

您现在很可能会看到上面的IllegalStateException 缺少res00000.dat。

请注意,滚动ZipInputStream 时没有理由手动调用closeEntry(),因为getNextEntry() 已经在后台执行此操作。来自 JDK 11 源代码:

public ZipEntry getNextEntry() throws IOException {
    ensureOpen();
    if (entry != null) {
        closeEntry();
    }
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2015-09-02
    • 2013-06-05
    相关资源
    最近更新 更多