Redirecting System.out.println() output to a file in Java


The filed named out of the System class represents a standard output Stream, an object of the PrintStream class.

The println() method of this accepts any a value ( of any Java valid type), prints it and terminates the line.

By default, console (screen) is the standard output Stream (System.in) in Java and, whenever we pass any String value to System.out.prinln() method, it prints the given String on the console.

Redirecting System.out.println()

The setOut() method of the System class in java accepts an object of the PrintStream class and makes it the new standard output stream.

Therefore, to redirect the System.out.println() output to a file −

  • Create an object of the File class.

  • Instantiate a PrintStream class by passing the above created File object as a parameter.

  • Invoke the out() method of the System class, pass the PrintStream object to it.

  • Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.

Example

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
public class SetOutExample {
   public static void main(String args[]) throws IOException {
      //Instantiating the File class
      File file = new File("D:\\sample.txt");
      //Instantiating the PrintStream class
      PrintStream stream = new PrintStream(file);
      System.out.println("From now on "+file.getAbsolutePath()+" will be your console");
      System.setOut(stream);
      //Printing values to file
      System.out.println("Hello, how are you");
      System.out.println("Welcome to Tutorialspoint");
   }
}

Output

From now on D:\sample.txt will be your console
raja
Published on 10-Oct-2019 14:46:47
Advertisements