读取ZipEntry中的String:java.io.IOException:Stream关闭

时间:2016-08-24 11:32:53

标签: java inputstream

我有一个servlet,它接受包含XML文件的ZIP文件。我想阅读那些xml文件的内容,但我得到一个java.io.IOException:Stream关闭。

我得到这样的ZIP:

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

我这样读了:

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

输出:

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)

我的问题

为什么我在这条线上得到这个例子?

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

我错过了什么?

1 个答案:

答案 0 :(得分:5)

您正在使用zis包裹BufferedReader,因此当您关闭br时,zis也会关闭。

因此删除br.close迭代将继续进行,没有任何异常。