VOOZH about

URL: https://www.geeksforgeeks.org/java/redirecting-system-out-println-output-to-a-file-in-java/

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


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 Image

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

Output:

👁 Image

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
Article Tags: