Could I duplicate or intercept an output stream in Java?

后端 未结 2 1736
一个人的身影
一个人的身影 2021-01-18 04:13

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 achiev

2条回答
  •  孤城傲影
    2021-01-18 05:04

    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.

提交回复
热议问题