Tuesday 29 July 2014

How I can redirect my console output to a File?

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;

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

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.setOut(ps);
  System.out.println("This goes to out.txt");

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


No comments:

Post a Comment