aspose file tools*
The moose likes I/O and Streams and the fly likes Accidentally closing System.out Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Accidentally closing System.out" Watch "Accidentally closing System.out" New topic
Author

Accidentally closing System.out

Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

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?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

That's a really good idea. Thanks Jim!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accidentally closing System.out
 
Similar Threads
HTTP get Request
Buffering streams and writers...
what happens in out.flush()?
Entities in attribute values issue in Sax parser
JSP with large data loads slow in Solaris10 OS , we are using Jrun4 and nested logic:iterate