关闭嵌套流也会关闭其父流? [英] Closing a nested stream closes its parent streams too?

查看:30
本文介绍了关闭嵌套流也会关闭其父流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OutputStream fos;输出流bos;输出流 zos;尝试 {fos = new FileOutputStream(anyFile);bos = 新的 BufferedOutputStream(fos);zos = 新的 ZipOutputStream(bos);} 最后 {如果(佐斯!= null){zos.close();//+ 异常处理}}

关闭 zos 是否也会自动关闭 bosfos,还是我需要手动关闭它们?

解决方案

是的,确实如此.它的 Javadoc 说:><块引用>

关闭 ZIP 输出流以及被过滤的流.

此外,BufferedOutputStream 的 Javadoc 说:

<块引用>

关闭此输出流并释放与该流关联的所有系统资源.

FilterOutputStreamclose方法调用其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 of FilterOutputStream calls its flush method, and then calls the close 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆