To redirect System.out.println() output to a file in Java instead to console?
The internal working of System.out.println():
System: java.lang package contains the class System with it's defination.
out: out is a public and static variable of System class. out is an instance of PrintStream class. Printstream class provides methods to write data to another stream. out can be referred as "standard" output stream.
println: println is a public method of Printstream class which is called by out to print the string to the console.
System.out.println() generally prints messages to the console but it can be used to print messages to other sources also, the only change required is to reassign the standard output by using System.setOut method of System class.
Syntax of System.setOut method:
System.setOut(PrintStream p);
Program to redirect output of System.out.println() to a text file.
import java.io.*;
public class SystemFact
{
public static void main(String a[]) throws FileNotFoundException
{
PrintStream o = new PrintStream(new File("A.txt")); //File object created
PrintStream console = System.out; // store current standard output
System.setOut(o); // o is assigned to output stream
System.out.println("This will be written to the text file");
System.setOut(console); //reassgn the standard output
System.out.println("This will be written on the console!");
}
}
0 Comment(s)