I have one function whose return type is VOID and it prints directly on console.
However I need that output in string so that I can work on it.
As I cant make any changes with function with return type is VOID so I have to redirect that output to string.
How can I redirect it in JAVA?
There are many questions regarding redirecting stdout to string but they redirect only input taken from user and not output of some function...
Here is a utility Class named ConsoleOutputCapturer. It allows the output to go to the existing console however behind the scene keeps capturing the output text. You can control what to capture with the start/stop methods. In other words call start to start capturing the console output and once you are done capturing you can call the stop method which returns a String value holding the console output for the time window between start-stop calls. This class is not thread-safe though.
If the function is printing to
System.out
, you can capture that output by using theSystem.setOut
method to changeSystem.out
to go to aPrintStream
provided by you. If you create aPrintStream
connected to aByteArrayOutputStream
, then you can capture the output as aString
.Example:
This program prints just one line: