Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout to a string in Java

Tags:

java

stdout

I know how to redirect the stdout to a file, but I have no idea on how to redirect it to a string.

like image 253
Fengqian Li Avatar asked Nov 15 '10 10:11

Fengqian Li


People also ask

How to redirect output in Java?

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.

How do I save console output to string 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 to redirect standard input in Java?

Whenever you want to redirect the standard output device from the screen to a file or printer, specify that symbol followed by the file or printer name on the command line. For example, redirect Print 's output to a Windows printer by issuing the following command line: java Print >prn .


1 Answers

Yes - you can use a ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); 

Then you can get the string with baos.toString().

To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding) constructor, and baos.toString(encoding)

If you want to revert back to the original stream, use:

System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); 
like image 143
Bozho Avatar answered Sep 21 '22 03:09

Bozho