无法从ZIP文件输入流读取文件

时间:2018-11-06 22:04:14

标签: java zip unzip zipfile

我有一个要读取的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 Test bank文件:

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您的代码当前无法处理缺少的条目。它只是默默地滚动到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的情况。

请注意,滚动closeEntry()时没有必要手动调用ZipInputStream,因为getNextEntry()已经在后台进行了操作。从JDK 11源代码中:

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