【问题标题】:Getting java.io.IOException: Stream closed error without explicitly closing it获取 java.io.IOException: Stream closed error without显式关闭它
【发布时间】:2018-06-22 08:19:56
【问题描述】:

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

【问题讨论】:

  • 您是否缺少代码?因为您只检查第一个流条目。循环遍历 zipEntries,而不仅仅是一个条目
  • 在您的第二次尝试资源中,您将 zipInputStream 包装到 BufferedInputStream 中,该 BufferedInputStream 在尝试后关闭并关闭也用于 zipInputStream 的底层流
  • 此外,您似乎正在使用 try 块内的整个流,而不仅仅是条目
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建 minimal reproducible example。使用edit 链接改进您的问题 - 不要通过 cmets 添加更多信息。谢谢!
  • 不要只将异常消息放在问题的标题中。将异常堆栈跟踪的相关部分添加到问题中,并清楚地确定您的代码抛出了哪一行。

标签: java fileoutputstream zipinputstream


【解决方案1】:

您正在使用语法 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

【讨论】:

  • @GhostCat 我添加了更多解释。
  • 鉴于我们在这里掌握的信息量,我现在倾向于同意你的观点 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 2020-08-11
  • 1970-01-01
  • 2023-03-25
  • 2014-05-18
  • 1970-01-01
  • 2018-11-12
相关资源
最近更新 更多