Search code examples
javasystem

Intercept system.out in java


I have a method that has system.out and it's used in main. How can I intercept that print and assign it to a String variable? I also do not want it to be printed.

public void print()
System.out.println("hello");

---main---
print(); // need to intercept this 
String str = print(); // need assign the contents of the print() to str and not show the contents of print in the console

Edit: Due to some restrictions, I cannot create .txt and I cannot change the code of the method. I need to make all the changes in main


Solution

  • 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.