Intercept system.out in java [duplicate]

You can call System.setOut() to change the PrintStream used by System.out. You probably also want to call setErr() to the same PrintStream.

To illustrate, let us use a standard “Hello World” program.

public static void main(String[] args) {
    System.out.println("Hello World");
}

Output

Hello World

We now replace the output print stream with a print stream that captures all the output in a buffer. We do keep a copy of the original print stream so we can print something for real at the end.

public static void main(String[] args) {
    PrintStream oldSysOut = System.out;
    ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
    try (PrintStream sysOut = new PrintStream(outBuf, false, StandardCharsets.UTF_8)) {
        System.setOut(sysOut);
        System.setErr(sysOut);
        
        // Normal main logic goes here
        System.out.println("Hello World");
    }
    String output = new String(outBuf.toByteArray(), StandardCharsets.UTF_8);
    oldSysOut.print("Captured output: \"" + output + "\"");
}

Output

Captured output: "Hello World
"

As can be seen here, all the output was captured, including the linebreak from the println() call.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top