I know how to redirect the stdout to a file, but I have no idea on how to redirect it to a string.
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 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!
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 .
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)));
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