Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect console output to string in Java

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?

like image 310
SRK Avatar asked Jan 03 '12 05:01

SRK


People also ask

How to write console output to a String 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!

How do you store console output in variables?

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.

How do I store system out Println output?

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.


1 Answers

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! 
like image 171
Ernest Friedman-Hill Avatar answered Nov 08 '22 19:11

Ernest Friedman-Hill