Re: Why should close() close the underlying stream?
Eric Sosman wrote:
Xiao Ma wrote:
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.
[...]
The people who designed java.io apparently felt that
such cases were a small minority, and chose to simplify
matters for what they considered the much more common case.
If you need the "one at a time" discipline, you can
get it without much work. Just extend FileOutputStream (or
whatever) with a class of your own that inherits almost all
its methods from the superclass, but overrides close() and
ignores it. If desired you could add a reallyClose() method
that forwards to super.close(), and/or a getActualStream()
method that returns the superclass instance.
You can't return a superclass instance, however you probably should use
inheritance here anyway. You should probably implement an OutputStream
that delegates to another OutputStream except for close().
Using that approach, you could use reallyClose() or getDelegate().close()
Although, as has been mentioned, usually if you close a stream, you
really DO want to close the underlying streams too.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>