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 you create a PrintStream connected to a ByteArrayOutputStream , then you can capture the output as a String . Example: // Create a stream to hold the output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); // IMPORTANT: Save the old System. out!
If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution. Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.
Instantiate a PrintStream class by passing the above created File object as a parameter. Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.
If the function is printing to System.out
, you can capture that output by using the System.setOut
method to change System.out
to go to a PrintStream
provided by you. If you create a PrintStream
connected to a ByteArrayOutputStream
, then you can capture the output as a String
.
Example:
// Create a stream to hold the output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); // IMPORTANT: Save the old System.out! PrintStream old = System.out; // Tell Java to use your special stream System.setOut(ps); // Print some output: goes to your special stream System.out.println("Foofoofoo!"); // Put things back System.out.flush(); System.setOut(old); // Show what happened System.out.println("Here: " + baos.toString());
This program prints just one line:
Here: Foofoofoo!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With