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

标签 java inputstream

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

我的问题

为什么我在这条线上得到了这个异常(exception)?

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

我错过了什么?

最佳答案

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

因此删除 br.close 迭代将毫无异常(exception)地继续进行。

关于java - 读取 ZipEntry 中的字符串 : java. io.IOException: Stream closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39122184/

相关文章:

java - 何时使用缓冲区以及有何用途

Java 在 IOException 之后重试

java - 实时绘制图表,随着时间的推移向后移动点

java - Eclipse 没有构建 aidl 文件

java - 使用 Struts2 将对象添加到列表

java - 如何创建受约束的 InputStream 以只读取文件的一部分?

java - InputStream 到 servletInputStream

java - 将字符串从 InputStream 映射到 ExecutorService

java - 发布自定义事件并在基于 Spring MVC 的 Rest 应用程序中异步处理它

java - 从 java 中的标准输入读取字符串和原始字节