How to capture and store console output, System.out.println()

By xngo on February 21, 2019

In Java, every string that passes through System.out.println() is stored in System.out. So, to get all strings, simply use System.out.toString() function. You can also swap in and out the console stream using System.setOut(). Examples below show how to get all strings called by System.out.println() and swap with another console stream.

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
 
public class ConsoleTutorial
{
 
    public static void main(String[] args){
 
        // Display something in initial console.
        System.out.println("One - Previous console");
 
        // Preserve current console which contains 'One - Previous console'.
        PrintStream previousConsole = System.out;
 
        // Set the standard output to use newConsole.
        ByteArrayOutputStream newConsole = new ByteArrayOutputStream();
        System.setOut(new PrintStream(newConsole));
 
        // From here on, all System.out.println() calls will be stored in newConsole.
        //  Note: The output "Two - New console" you see from the console doesn't  
        //        come from this line but from the line "previousConsole.println(...);"
        System.out.println("Two - New console");
 
        previousConsole.println(newConsole.toString()); // Display output of newConsole.
 
        // Restore back the standard console output.
        System.setOut(previousConsole);
 
        // Test print to console.
        System.out.println("Three - Restored console");
        System.out.println(newConsole.toString());
 
    }
}

Output

One - Previous console
Two - New console
 
Three - Restored console
Two - New console

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/io/ConsoleTutorial.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.