关闭嵌套流也会关闭其父流? [英] Closing a nested stream closes its parent streams too?
问题描述
OutputStream fos;输出流bos;输出流 zos;尝试 {fos = new FileOutputStream(anyFile);bos = 新的 BufferedOutputStream(fos);zos = 新的 ZipOutputStream(bos);} 最后 {如果(佐斯!= null){zos.close();//+ 异常处理}}
关闭 zos
是否也会自动关闭 bos
和 fos
,还是我需要手动关闭它们?
是的,确实如此.它的 Javadoc 说:><块引用>
关闭 ZIP 输出流以及被过滤的流.
此外,BufferedOutputStream 的 Javadoc
说:
关闭此输出流并释放与该流关联的所有系统资源.
FilterOutputStream
的close
方法调用其flush
方法,然后调用其底层的close
方法输出流.
因此,当您关闭 ZipOutputStream
时,它会关闭您的 BufferedOutputStream
,进而关闭您的 FileOutputStream
.
OutputStream fos;
OutputStream bos;
OutputStream zos;
try {
fos = new FileOutputStream(anyFile);
bos = new BufferedOutputStream(fos);
zos = new ZipOutputStream(bos);
} finally {
if (zos != null) {
zos.close(); // + exception handling
}
}
Does closing zos
automatically closes bos
and fos
too, or do I need to close them manually?
Yes, it does. Its Javadoc says:
Closes the ZIP output stream as well as the stream being filtered.
Also, the Javadoc for BufferedOutputStream
says:
Closes this output stream and releases any system resources associated with the stream.
The
close
method ofFilterOutputStream
calls itsflush
method, and then calls theclose
method of its underlying output stream.
So when you close your ZipOutputStream
, it will close your BufferedOutputStream
, which will in turn close your FileOutputStream
.
这篇关于关闭嵌套流也会关闭其父流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!