redirect console output to string in java

redirect console output to string in java

how to capture console output in java

// how to assign the console output to a variable

// 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("Hello Java world!");

// Put things back
System.out.flush();
System.setOut(old);

// print the console output
System.out.println("Here: " + baos.toString());
S‮o‬urce:www.lautturi.com
Created Time:2017-09-02 11:27:34  Author:lautturi