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

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

问题描述

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
    }
}

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

Does closing zos automatically closes bos and fos too, or do I need to close them manually?

推荐答案

是的.其 Javadoc 说:

Yes, it does. Its Javadoc says:

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

Closes the ZIP output stream as well as the stream being filtered.

此外, BufferedOutputStream的Javadoc 说:

Also, the Javadoc for BufferedOutputStream says:

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

Closes this output stream and releases any system resources associated with the stream.

FilterOutputStreamclose方法调用其flush方法,然后调用其基础输出流的close方法.

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

因此,当您关闭ZipOutputStream时,它将关闭您的BufferedOutputStream,这又将关闭您的FileOutputStream.

So when you close your ZipOutputStream, it will close your BufferedOutputStream, which will in turn close your FileOutputStream.

这篇关于关闭嵌套流也会关闭其父流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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