fileoutputstream正在获取java。木卫一。IOException:流关闭错误,但未显式关闭它
我的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();
}
# 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.javahttps://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html