Try a block that throws an IOException thread exception

My question is about this exception

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)

So, we recently updated our code for Java 7, and we had to implement a try block to declare a ZipFile. This seems to cause the input stream to close where it was not before when there was no try block. Not sure if I understand why when it is declared in front of the block. Can someone explain or suggest a solution?

    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
source share
2 answers

In the current code, you are using the try-with-resources statement , so your ZipFile docsZipcloses as soon as it is trycompleted.

docsZip try, ( , - out.close().

+1

ZipFile#close:

ZIP , getInputStream.

(Java 7 try-with-resources close .)

+1

Source: https://habr.com/ru/post/1695888/


All Articles