Could I duplicate or intercept an output stream in Java?
Asked Answered
T

2

7

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?

Twitt answered 26/7, 2012 at 16:20 Comment(2)
please share the code in which you want to implement thisRevocable
absolutely possible, implementations will depend on the specifics.Manganese
S
6

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.

Springer answered 26/7, 2012 at 16:29 Comment(1)
Thanks for noticing, I edited with a slightly different answerSpringer
B
2

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

Bioscope answered 19/10, 2012 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.