简体   繁体   中英

Unable to read files from ZIP file input stream

I have a Zip file that I am trying to read. 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.

This is what I have tried so far. Instead of printing the contents of res00000.dat , it prints an empty line. 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. It is a Blackboard Test bank file that I'm attempting to parse:

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. 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 .

Do note that there is no reason to call closeEntry() manually when scrolling the ZipInputStream as getNextEntry() already does it under the hood. From JDK 11 source code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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