Search code examples
javafileoutputstreamzipinputstream

Getting java.io.IOException: Stream closed error without explicitly closing it


My zipInputStream is getting closed after writing the first file itself even though I am not closing any of the streams.

 ZipInputStream zipInputStream = new ZipInputStream(inputStream); 
 ZipEntry zipEntry = zipInputStream.getNextEntry();
  while (zipEntry != null) {

        modelFolderName = <somefoldername>
        modelFileName = <somefilename>

        String FILE_STORAGE_LOCATION = env.getProperty("workspacePath");

        File folder = new File(FILE_STORAGE_LOCATION + "/" + modelFolderName );
        if(!folder.exists()) {
            folder.mkdirs();
        }

        try (FileOutputStream fout=new FileOutputStream(FILE_STORAGE_LOCATION + "/" +  modelFolderName + "/" + modelFileName)) {
            try (BufferedInputStream in = new BufferedInputStream(zipInputStream)) {
              byte[] buffer = new byte[8096];
              while (true) {
                int count = in.read(buffer);
                if (count == -1) {
                  break;
                }
                fout.write(buffer, 0, count);
              }
            }
        }
        zipEntry = zipInputStream.getNextEntry();
    }

Solution

  • You are using the syntax try-with-resource. Everything inside the parenthesis will be closed automatically as if there is a finally block to close it.

    When in is closed in the implicit finally block, zipInputStream will also be closed because BufferedInputStream is a subclass of FilterInputStream, which closes its source when itself get closed.

    (In general, most classes implementing Closable release any resources associated when close is called)

    To see the implementation of FilterInputStream::close https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/io/FilterInputStream.java

    https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html