我的问题是关于这个例外
java.io.IOException: Stream closed
java.util.zip.InflaterInputStream.ensureOpen(InflaterInputStream.java:67)
java.util.zip.InflaterInputStream.read(InflaterInputStream.java:142)
java.io.FilterInputStream.read(FilterInputStream.java:107)
com.avnet.css.servlet.PartNotificationFileServlet.doGet(PartNotificationFileServlet.java:51)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
所以我们最近升级了Java 7的代码,我们必须为ZipFile声明实现一个try块。这似乎导致输入流关闭,而在没有尝试阻止之前它没有。在块之前声明它时,不确定我理解为什么。任何人都可以解释或提供解决方案吗?
String uri = req.getRequestURI();
String[] tokens = uri.split("/");
String folder = tokens[tokens.length - 2];//req.getParameter("folder");
String filename = tokens[tokens.length - 1];req.getParameter("filename");
Properties properties = new CSSProperties();
InputStream inputStream = null;
if(!folder.contains("_AVT")){
//below is the new try block, when the declaration inside the parenthesis is on its own, instead of inside try, it works fine.
try (ZipFile docsZip = new ZipFile(new File(properties.getProperty(PCN_DIR) + File.separator + folder + File.separator + "Documents.zip"))) {
ZipEntry entry = docsZip.getEntry(filename);
if (entry != null)
inputStream = docsZip.getInputStream(entry);
}
}
else{
String decodedFileName = URLDecoder.decode(filename, "UTF-8");
File file = new File(properties.getProperty(PCN_DIR) + File.separator + folder + File.separator + decodedFileName);
if(file.exists())
inputStream = new FileInputStream(file);
}
if(inputStream != null){
resp.setHeader("Content-Type", MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename));
ServletOutputStream out = resp.getOutputStream();
byte[] buffer = new byte[2048];
int read;
while ((read = inputStream.read(buffer)) > 0) //this is line 51, where the error occurs
out.write(buffer, 0, read);
inputStream.close();
out.close();
}
答案 0 :(得分:1)
这是ZipFile#close
中记录的行为:
关闭此ZIP文件将关闭先前通过getInputStream方法调用返回的所有输入流。
(Java 7 try-with-resources语句在块结束时自动调用close
。)
答案 1 :(得分:1)
在当前代码中,您使用的是try-with-resources statement,因此只要ZipFile docsZip
完成,您的try
就会关闭。
当您将docsZip
的声明置于try
之内时,它将不会被关闭(请注意,这应该在out.close()
之后的某处完成。