Capturing contents of standard output in Java

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);
  }
}

Leave a Comment