Saturday, 27 February 2016

How do I redirect standard output to a file using System.out.println()?

System.out.println() is used to print messages on the console.

System is a class defined in the java.lang package. out is an instance of PrintStream, which is a public and static member of the class System. As all instances of PrintStream class have a public method println().

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.


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

public class SetPrintStream {
  public static void main(String[] args) throws FileNotFoundException{
           System.out.println("Print on console");
          
           // Store console print stream.
           PrintStream ps_console = System.out;
          
           File file = new File("file.txt");
           FileOutputStream fos = new FileOutputStream(file);
          
           // Create new print stream for file.
           PrintStream ps = new PrintStream(fos);
          
           // Set file print stream.
           System.setOut(ps);
           System.out.println("Print in the file !!");

           // Set console print stream.
           System.setOut(ps_console);
           System.out.println("Console again !!");
 }
}

Output:
Print on console
Console again !!
    
new file.txt will be created.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...