首页 > 解决方案 > 获取 java.io.IOException: Stream closed error without显式关闭它

问题描述

即使我没有关闭任何流,我的 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();
    }

标签: javafileoutputstreamzipinputstream

解决方案


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

in在隐式 finally 块中关闭时,zipInputStream也将被关闭,因为BufferedInputStream它是 的子类FilterInputStream,它在自身关闭时关闭其源。

(一般来说,大多数实现类在被调用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


推荐阅读