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