How to redirect standard output in a java program.

Question:
How to redirect standard output in a java program.

Code:
import java.io.*;
 
public class RedirectStandardOutput {
  public static void main(String args[]) throws FileNotFoundException {
 
    PrintStream out = new PrintStream(
      new BufferedOutputStream(
        new FileOutputStream("output.txt")));
    System.setOut(out);
 
    System.out.println("Hello World.");
    System.out.println("This is a test.");
    System.out.println("Good bye.");
 
    out.close();
  }
}

Output:
$ java RedirectStandardOutput

$ cat output.txt 
Hello World.
This is a test.
Good bye.