• Post Reply Bookmark Topic Watch Topic
  • New Topic

direct System.out to file AND console  RSS feed

 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

i was wondering what is the best way to direct all calls on system.out to a file, but still also show the output in the console ...

i came up with the following code, but it looks somehow cumbersome, since you would have to overwrite all implemented mehtods




the implementing code would look like this




is there a better way to achieve this ?
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i came up with the following code, but it looks somehow cumbersome, since you would have to overwrite all implemented mehtods


Yea, printstream has a lot of methods... it may be better to write a multi output stream that overrides filter output stream.

Keep in mind that system out is, by default, just a printstream around a file output stream with the STDOUT file descriptor. So, instead of a multi printstream that contains the original printstream and another print stream around a file output stream, a better option would be a print stream around a multi output stream that contains the file output stream of stdout and file output stream of the file.

Something like this...



Only 5 methods to override...

Henry
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey,

i hope i got that right ...
the general idea of the implementation is correct but instead of overriding PrintStream I override FilterOutputStream to have less methods to overwrite ?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian Janisch wrote:hey,

i hope i got that right ...
the general idea of the implementation is correct but instead of overriding PrintStream I override FilterOutputStream to have less methods to overwrite ?


Yup... And BTW, you can't assign to the System.out variable -- it is final and can't be reassigned. You have to use the setOut() method instead (to reassign the variable).

Henry
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
true, i forgot about that part ...

okay cool thank you
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!