Closing a nested stream closes its parent streams too?

我与影子孤独终老i 提交于 2019-12-22 04:31:09

问题


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?


回答1:


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.




回答2:


Yes.

ZipOutputStream.close() method is specified by Closeable.close() which:

Closes this stream and releases any system resources associated with it.

The same applies to BufferedOutputStream.close(), a method inherited from FilterOutputStream.




回答3:


Closing the wrapper stream automatically closes the inner stream.

So, in your case you only need to close ZipOutputStream. Closing a stream twice does not throw an exception hence closing an inner stream again (although unnecessary) works as well.

Here's what happens when you instantiate a ZipOutputStream

public ZipOutputStream(OutputStream out) {
    this.out = out; // BufferedOutputStream reference saved
}

Here's the implementation of ZipOutputStream.close()

public void close() throws IOException {
    try {
      flush();
    } catch (IOException ignored) {
    }
    out.close(); // BufferedOutputStream being closed
}

Similarly, BufferedOutputStream automatically closes the FileOutputStream through its inherited FilterOutputStream#close() which has been implemented as:

public void close() throws IOException {
    try {
      flush();
    } catch (IOException ignored) {
    }
    out.close(); // FileOutputStream being closed
}



回答4:


Yes it does. but strangely when i was running the fortify scan with find bug enabled it catches all these kind of wrapped and unclosed streams as high priority items to be fixed. Not sure why they do so



来源:https://stackoverflow.com/questions/18054184/closing-a-nested-stream-closes-its-parent-streams-too

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!