问题
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 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
.
回答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