Knowledge Walls
John Peter
Pune, Maharashtra, India
How to redirect System.out.println data to File in Java with Example
2274 Views
How to redirect again to System console using System.setOut Method
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class SetOutBacktoSystemConsole {
    public static void main(String args[]) throws Exception{
     System.out.println("Printing on Console");
    
     PrintStream printStream = new PrintStream(new FileOutputStream("d:/my_data_out.txt"));
        System.setOut(printStream);
        
        System.out.println("Java");
        System.out.println("is");
        System.out.println("Quick");
       
        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
       
        System.out.println("Again I am back to Console");
    }
}
Output 
Console
Printing on Console
Again I am back to Console

On my_data_out.txt file
Java
is
Quick
SystemSetOutExample
import java.io.FileOutputStream;
import java.io.PrintStream;

public class SystemSetOutExample{
    public static void main(String args[]) throws Exception{    
        PrintStream printStream = new PrintStream(new FileOutputStream("d:/my_data_out.txt"));
        System.setOut(printStream);
        
        System.out.println("Java");
        System.out.println("is");
        System.out.println("Quick");
    }
}
My_data_out.txt 
Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details