【问题标题】:Read the String inside a ZipEntry: java.io.IOException: Stream closed读取 ZipEntry 中的字符串:java.io.IOException: Stream closed
【发布时间】:2016-08-24 11:32:53
【问题描述】:

我有一个 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) {

我错过了什么?

【问题讨论】:

    标签: java inputstream


    【解决方案1】:

    你正在用BufferedReader 包裹你的zis,所以当你关闭br,zis 也会关闭。

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

    【讨论】:

    • 就是这样。我应该将声明从循环中取出并在之后关闭它吗?有没有更好的方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2021-02-17
    • 1970-01-01
    • 2023-03-25
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多