Skip to content
Related Articles
Open in App
Not now

Related Articles

Redirecting System.out.println() Output to a File in Java

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 10 May, 2022
Improve Article
Save Article

System.out.println()  is used mostly to print messages to the console. However very few of us are actually aware of its working mechanism. We can use System.out.println() to print messages to other sources too, not just restricting it to the console. However, before doing so, we must reassign the standard output by using the following method of System class as provided below:


System.setOut(PrintStream p);

Note: PrintStream can be used for character output to a text file. 

  • System is a class defined in 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(), hence we can invoke the same on out as well. We can assume System.out represents the Standard Output Stream.


  1. Creation of File class object
  2. Instantiating PrintStream class by passing above object of File class as argument.
  3. Calling the out() method of System class by providing PrintStream object.
  4. Lastly, print the data using the print() method.    

The sample input file is as follows:



// Java Program to Demonstrate Redirection in
// System.out.println() By Creating .txt File
// and Writing to the file Using
// System.out.println()
// Importing required classes
// Main class
// SystemFact
public class GFG {
    // Main driver method
    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
        // using setOut() method
        // Display message only
            "This will be written to the text file");
        // Use stored value for output stream
        // Display message only
            "This will be written on the console!");


Tip: In a very similar fashion we can use System.out.println() to write to a Socket’s OutputStream as well.

This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article on or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!