I ran into this problem some time ago, and have never figured out a solution. Some libraries provide methods that take some sort of output stream, then write their data to that stream. For example Castor generates objects based on an XML schema. You can get the XML back by calling marshal(Writer out), on the root object. Typically, you pass it a FileWriter. However, if I want the output to go to the console, I can instead use: OutputStreamWriter ow = new OutputStreamWriter(System.out); The problem is when I close ow, it will also close the underlying stream, which is standard out. Even if I don't explicitly close ow, it will be closed when it is finalized. Here's a contrived example:
The output is: Before C The word "After" doesn't appear because System.out has already been closed. Is there a workaround for this problem?
I sometimes use a custom FilterOutputStream which overrides close() to do nothing (or, what the heck, do a flush() to be safe), rather than close the inner stream. Then add a method reallyClose() so that you can still close the inner stream if you really want to. Once you've made this class, you can wrap it around System.out (or any other stream you want) and pass it off to other methods without rear of premature closure. You can do the same thing with a FilterInputStream of course.