Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the String inside a ZipEntry: java.io.IOException: Stream closed

I have a servlet that accepts ZIP files that contains XML files. I would like to read the content of those xml files but I am getting a java.io.IOException: Stream closed.

I get the ZIP like this:

private byte[] getZipFromRequest(HttpServletRequest request) throws IOException {
    byte[] body = new byte[request.getContentLength()];
    new DataInputStream(request.getInputStream()).readFully(body);
    return body;
}

And I read it like this:

public static void readZip(byte[] zip) throws IOException {

    ByteArrayInputStream in = new ByteArrayInputStream(zip);
    ZipInputStream zis = new ZipInputStream(in);

    ZipEntry entry;

    while ((entry = zis.getNextEntry()) != null) {
        System.out.println(String.format("Entry: %s len %d", entry.getName(), entry.getSize()));

        BufferedReader br = new BufferedReader(new InputStreamReader(zis, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }
    zis.close();
}

The output:

Entry: file.xml len 3459
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test>
correct content of my xml file
</test>
java.io.IOException: Stream closed
    at java.util.zip.ZipInputStream.ensureOpen(ZipInputStream.java:67)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:116)
    at util.ZipHelper.readZip(ZipHelper.java:26)

My question

Why am I getting this exeption on this line ?

while ((entry = zis.getNextEntry()) != null) {

What did I miss ?

like image 330
Tim Avatar asked Aug 24 '16 11:08

Tim


1 Answers

You are wrapping your zis with BufferedReader so when you close br,zis will also close.

So remove br.close iteration will proceed without any exception.

like image 177
Poornima Avatar answered Nov 10 '22 06:11

Poornima