简体   繁体   English

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

[英]Unable to read files from ZIP file input stream

I have a Zip file that I am trying to read. 我有一个要读取的Zip文件。 I do not want to use a ZipFile because in the future, I would like to do this for data that is not from a file. 希望使用ZipFile ,因为在未来,我想因为这是不是从一个文件中的数据做到这一点。

This is what I have tried so far. 到目前为止,这是我尝试过的。 Instead of printing the contents of res00000.dat , it prints an empty line. 而不是打印res00000.dat的内容,而是打印一个空行。 I do not know how to fix this 我不知道该如何解决

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;

My ZIP file has only two files in it. 我的ZIP文件中只有两个文件。 It is a Blackboard Test bank file that I'm attempting to parse: 这是我尝试解析的Blackboard Test bank文件:

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

Can someone please help? 有人可以帮忙吗?

You code currently doesn't handle a missing entry. 您的代码当前无法处理缺少的条目。 It just silently scrolls to the end of a ZipInputStream so there is no way to tell what's happening. 它只是无声地滚动到ZipInputStream的末尾,因此无法判断发生了什么。 You could do following to get exception when an entry identified by name is missing: 当按名称标识的条目丢失时,可以执行以下操作以获取异常:

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");
}

You will most likely observe above IllegalStateException now for missing res00000.dat . 您很可能现在会在IllegalStateException上方观察到缺少res00000.dat

Do note that there is no reason to call closeEntry() manually when scrolling the ZipInputStream as getNextEntry() already does it under the hood. 请注意,滚动ZipInputStream时没有理由手动调用closeEntry() ,因为getNextEntry()已经在closeEntry()进行了操作。 From JDK 11 source code: 从JDK 11源代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM