Reading a line inside ZipEntry: java.io.IOException: stream closed

I have a servlet that accepts ZIP files containing XML files. I would like to read the contents of these XML files, but I get 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 as follows:

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

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 exemption on this line?

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

What did I miss?

+4
source share
1 answer

You wrap zis BufferedReader, so when you close brit also closes zis.

So the removal of the br.closeiteration will continue without any exceptions.

+3
source

Source: https://habr.com/ru/post/1652327/


All Articles