Java source code examples

Java source code samples. Java code examples.

Redirect standard output stream (System.out) to a file

* * * * * 1 votes

We can redirect the standard output stream System.out to a file either programatically or from the console.

programatically redirecting System.out

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

public class SystemExample {
	public static void main(String[] args) throws FileNotFoundException {
		PrintStream p = new PrintStream(new FileOutputStream(new File("c:\\temp\\out.log")));
		System.setOut(p);

		System.out.println("Hello World");
	}
}

or

Use the redirection operator >> from the console when executing the java program. For eg:

java SystemExample >> out.log

Tags: java.lang

Discuss This Code