How do I redirect standard output to a file?
Author: Deron Eriksson
Description: This Java tutorial describes how to redirect standard output to a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

System.out is a static PrintStream that writes to the console. We can redirect the output to a different PrintStream using the System.setOut() method which takes a PrintStream as a parameter. The RedirectSystemOut class shows how we can have calls to System.out.println() output to a file rather than to the console by passing System.setOut() a PrintStream based on a FileOutputStream.

package test;


public class RedirectSystemOut {

	public static void main(String[] args) throws FileNotFoundException {
		System.out.println("This goes to the console");
		PrintStream console = System.out;

		File file = new File("out.txt");
		FileOutputStream fos = new FileOutputStream(file);
		PrintStream ps = new PrintStream(fos);
		System.out.println("This goes to out.txt");

		System.out.println("This also goes to the console");

The execution of RedirectSystemOut is shown below. We can see the expected result in the console at the bottom and in the out.txt file above that.

Execution of RedirectSystemOut