How to redirect System.out to a file in Java?

Interview question: How to redirect System.out to a file in Java?

Basic Answer

There are two easy ways to redirect System.out to a file in Java:

1. Through console redirection. For example if your Java application lived in a Jar called “somejar.jar”, you could simple type the following command on the command-line console and have the output of the application redirected to the file output.txt:


java -jar somejar.jar > output.txt

2. Programmatically by updating the System.out output stream. This can be accomplished by setting the output stream to a file. See below:


System.setOut(new PrintStream(new File("output.txt")));

Further Explanation:

Both approaches outlined above will effectively redirect the output of the Java application to a text file. The first approach is more flexible in that it allows the client of the application to change the output location. They can invoke the application and have the output printed to the console, saved to a file, or used as an input into another application all through built-in console commands.

The second approach enforces consistency and removes the details of where the application writes to from the client of the application. This can be useful when you don’t want the user to be able to change where the output is written to. It does, however, limit the flexibility of the application.