File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accidentally closing System.out

 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a really good idea. Thanks Jim!
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic