读取 ZipEntry 中的字符串:java.io.IOException: Stream closed

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

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

我得到的 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) {

我错过了什么?

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

因此删除 br.close 迭代将毫无例外地进行。