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


Redirecting standard error can be accomplished by calling System.setErr() with a PrintStream. One common task is to have this PrintStream write standard error to a file, as demonstrated by RedirectSystemErr.

RedirectSystemErr.java

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class RedirectSystemErr {

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

		File file = new File("err.txt");
		FileOutputStream fos = new FileOutputStream(file);
		PrintStream ps = new PrintStream(fos);
		System.setErr(ps);

		System.err.println("This goes to err.txt");

		try {
			throw new Exception("Exception goes to err.txt too");
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.setErr(console);
		System.err.println("This also goes to the console");
	}
}

After executing RedirectSystemErr, the following was displayed in the console.

This goes to the console
This also goes to the console

After execution, the err.txt file was created and contained the following text.

err.txt

This goes to err.txt
java.lang.Exception: Exception goes to err.txt too
	at test.RedirectSystemErr.main(RedirectSystemErr.java:21)