我写了第一个文件后,我的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.java的实施情况https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html