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

Last Updated : 12 Jun, 2026

In Java, System.out.println() is commonly used to display output on the console. However, Java allows us to redirect this output to other destinations like files or network streams. This is achieved using System.setOut() with a PrintStream.

  • PrintStream can write data to files, sockets, or other streams.
  • System is a class defined in java.lang package.
  • Original console output can be restored by saving the default stream.

Syntax

System.setOut(PrintStream p);

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

Procedure

  • Create a File object representing the target file.
  • Create a PrintStream object using the file.
  • Store the original System.out stream (optional but recommended).
  • Redirect output using System.setOut(PrintStream).
  • Use System.out.println() to write into the file.
  • Restore original output stream if needed. 

The sample input file is as follows:

Example: Java Program to Demonstrate Redirection in System.out.println() By Creating .txt File and Writing to the file Using System.out.println()

Java
// Importing required classes
import java.io.*;

// 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
        System.setOut(o);

        // Display message only
        System.out.println(
            "This will be written to the text file");

        // Use stored value for output stream
        System.setOut(console);

        // Display message only
        System.out.println(
            "This will be written on the console!");
    }
}

Output:

Explanation: The program redirects the standard output stream to the file A.txt, causing the first println() statement to write to the file. It then restores the original console output stream, so the second println() statement is displayed on the console.

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

Advantages of System.out.println()

  • Enables logging program output directly into files.
  • Useful for debugging large applications.
  • Helps in storing execution results permanently.
  • Supports output redirection without changing existing println() calls.
  • Can redirect output to other streams like sockets or logs.
Comment