Java program to redirecting System.out.println() output to a file

System.out.println() is mainly used to print console messages. However, very few of us are aware of its mechanism of action.

  • The system is a class defined in java.lang package.
  • out is an instance of PrintStream which is a public and static member of the system class.
  • Since all instances of the PrintStream class have a public println() method, we can call the same on exit. We can assume that System.out is the standard output stream.

An interesting fact regarding the above topic is that we can use System.out.println() to print messages to other sources (not just the console). However, before doing this, we need to reassign the standard output to the System class using the following method:

System.setOut(PrintStream p);

PrintStream can be used to display characters in a text file. Under program create A.txt file and save it with System.out.println (

// Java program to demonstrate redirection in System.out.println()
import java.io.*;

public class SystemFact
{
	public static void main(String arr[]) throws FileNotFoundException
	{
		// Creating a File object that represents the disk file.
		PrintStream o = new PrintStream(new File("A.txt"));

		// Store current System.out before assigning a new value
		PrintStream console = System.out;

		// Assign o to output stream
		System.setOut(o);
		System.out.println("This will be written to the text file");

		// Use stored value for output stream
		System.setOut(console);
		System.out.println("This will be written on the console!");
	}
}

In a very similar way, we can use System.out.println() to write an OutputStream to Sockets.

Submit Your Programming Assignment Details