Java I/O How to - Redirect the output of System.out to a file








Question

We would like to know how to redirect the output of System.out to a file.

Answer

//from w ww . j  a  va 2  s  .c  o m
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

public class Main {
  public static void main(String[] args) {
    File file = new File("C:\\temp\\debug.txt");
    try {
      PrintStream ps = new PrintStream(file);
      System.setOut(ps);
    } catch (IOException e) {
    }
    System.out.println("To File");
  }
}

The code above generates the following result.