Capturing contents of standard output in Java

Shailesh Tainwala picture Shailesh Tainwala · Mar 22, 2011 · Viewed 21k times · Source

I am invoking a function that is printing some string in my console/standard output. I need to capture this string. I cannot modify the function that is doing the printing, nor change runtime behavior through inheritance. I am unable to find any pre-defined methods that will allow me to do this.

Does the JVM store a buffer of printed contents?

Does anyone know of a Java method that will aid me?

Answer

Andreas Dolk picture Andreas Dolk · Mar 22, 2011

You can redirect the standard output by calling

System.setOut(myPrintStream);

Or - if you need to log it at runtime, pipe the output to a file:

java MyApplication > log.txt

Another trick - if you want to redirect and can't change the code: Implement a quick wrapper that calls your application and start that one:

public class RedirectingStarter {
  public static void main(String[] args) {
    System.setOut(new PrintStream(new File("log.txt")));
    com.example.MyApplication.main(args);
  }
}