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

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

我的 zipInputStream 在写入第一个文件后关闭,即使我没有关闭任何流。

 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();
    }

您正在使用语法 try-with-resource。括号内的所有内容都会自动关闭,就好像有一个 finally 块来关闭它一样。

in在隐式finally块中关闭时,zipInputStream也将被关闭,因为BufferedInputStreamFilterInputStream的子类,当它自己关闭它的源时关闭。

(一般来说,大多数 类 实现 Closable 会在调用 close 时释放任何关联的资源)

查看执行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