X
Xiao Ma
A stream may have an underlying stream. For example,
FileOutputStream fos = new FileOutputStream("foo");
BufferedOutputStream bos = new BufferedOutputStream(fos);
fos is the underlying stream for bos.
Now if I call bos.close(), it will also close its underlying stream.
Why should the underlying stream be closed? I can think of some cases
where I want to continue to write to the underlying output stream
after I close the "outer" output stream.
I know it's useful if people do
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("foo"));
and you don't have a handle on the underlying stream. But you can
always define a variable for the underlying stream.
I have a method that allows the caller to pass in an output stream.
Then I want to use a BufferedOutputStream to write to it. After that,
I should close the BufferedOutputStream before exiting the method. But
that closes the output stream passed in by the caller and the caller
can no longer write to it. For example,
void foo(OutputStream out) {
try {
BufferedOutputStream bout = new BufferedOutputStream(out);
bout.write(blahblah);
}
finally {
bout.close(); // I should close any stream I created but
this closes the underlying stream, too.
}
}
FileOutputStream fos = new FileOutputStream("foo");
BufferedOutputStream bos = new BufferedOutputStream(fos);
fos is the underlying stream for bos.
Now if I call bos.close(), it will also close its underlying stream.
Why should the underlying stream be closed? I can think of some cases
where I want to continue to write to the underlying output stream
after I close the "outer" output stream.
I know it's useful if people do
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("foo"));
and you don't have a handle on the underlying stream. But you can
always define a variable for the underlying stream.
I have a method that allows the caller to pass in an output stream.
Then I want to use a BufferedOutputStream to write to it. After that,
I should close the BufferedOutputStream before exiting the method. But
that closes the output stream passed in by the caller and the caller
can no longer write to it. For example,
void foo(OutputStream out) {
try {
BufferedOutputStream bout = new BufferedOutputStream(out);
bout.write(blahblah);
}
finally {
bout.close(); // I should close any stream I created but
this closes the underlying stream, too.
}
}