Could I duplicate or intercept an output stream in Java?

∥☆過路亽.° 提交于 2019-12-19 17:40:44

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11673697/could-i-duplicate-or-intercept-an-output-stream-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!