I have one method whose return type is void and it prints directly on console.
However I need that output in a String so that I can work on it.
As I can’t make any changes to the method with return type void I have to redirect that output to a String.
How can I redirect it in Java?
If the function is printing to
System.out, you can capture that output by using theSystem.setOutmethod to changeSystem.outto go to aPrintStreamprovided by you. If you create aPrintStreamconnected to aByteArrayOutputStream, then you can capture the output as aString.Example:
This program prints just one line: