java - 获取 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();
}
解决方案
您正在使用语法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
推荐阅读
- docker - 容器以代码 0 退出,我的应用程序由主机操作系统提供
- java - 中继 S3 存储桶访问还是为用户提供直接访问链接?
- java - PDF/A-3A 文档的 PAdES LTV 签名产生无效签名
- ios - 未调用 ViewController 文件
- node.js - 我正在尝试对猫鼬数据库中的数据进行排序,并使用 find() 函数获取输出,但我想使用 paginate() 函数对数据进行排序
- react-native - 在 react-native 上将 base64 转换为 blob 时获取错误
- python - Self Attention 不如 RNN 好?
- volttron - 在 Volttron 平台中导入 Pandas 时出错
- xml - 如何使用 XML::Simple 根据 Perl 中的 XML 属性内容修改 XML 元素?
- visual-studio-code - 自动格式化,使用 Visual Studio Code 自动换行(在 Mac 上)