Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could I duplicate or intercept an output stream in Java?

I want to intercept the standard output stream, then copy the content to another stream, but I also hope to keep the standard output stream like the original. Could I achieve that in Java?

like image 482
Auguste Avatar asked Jul 26 '12 16:07

Auguste


2 Answers

You can use something like the example of TeeOutputStream explained here Writing Your Own Java I/O Stream Classes

Basically you create a TeeOutputStream, give it your stream and current System.out then use System.setOut with the new stream.

Anything written to System.out will be written to the original System.out as well as your stream so you can do whatever you want with it

Edit:

Oracle took off this page, It is also possible to use TeeOutputStream from Apache Commons to do the same thing without adding any code.

like image 109
Aviram Segal Avatar answered Oct 07 '22 17:10

Aviram Segal


Take a look at this package: org.apache.commons.io.output. I think that TeeOutputStream is what you're looking for.

like image 33
yegor256 Avatar answered Oct 07 '22 18:10

yegor256