I have a Java program that outputs some text into console. It uses print, println, and some other methods to do this.
At the end of the program , I want to read all the text in console and copy it into a String buffer. How could I do this in Java ? I need to read stdout and stderr separately.
Ok, this was a fun problem. Dosen’t seem to be an elegant way of solving it for all
PrintStreammethods at once. (Unfortunately there is noFilterPrintStream.)I did write up an ugly reflection-based workaround though (not to be used in production code I suppose 🙂
…that can be used like this:
Resulting output:
(Note though, that the
outfield inFilterOutputStreamis protected and documented, so it is part of the API 🙂