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

To print output to the console in Java, use the System.out.println() function. For logging or auditing purposes, you could, nevertheless, choose to reroute this output to a file in some circumstances. The PrintStream class can be used to do this. In this section, we will discuss the process of redirecting System.out.println() output to a file, complete with examples and a thorough explanation.

Understanding PrintStream

The PrintStream class provides methods to print representations of various data types to an output stream. By default, System.out is a PrintStream that prints to the console. To redirect output, we can replace the standard output stream with a PrintStream that writes to a file.

Steps to Redirect Output

  1. Create a PrintStream Object: Create a PrintStream object that points to the desired output file.
  2. Set System.out to the PrintStream: Use System.setOut(PrintStream) to replace the standard output stream with the file-based PrintStream.
  3. Write Output: Continue using System.out.println() as usual. The output will be redirected to the specified file.

File Name: RedirectOutput.java

Output:

 
This message is back to the console.   

Output.txt

 
This is a message to the file.   

Explanation

The output of System.out.println() can be redirected from the console to a file and back again using this Java program. Importing the required classes for file and stream processing is the first step.

A PrintStream object called fileOut is created inside the main method in order to write to the output.txt file. ConsoleOut stores the original System.out stream for potential restoration at a later time. All System.out.println() calls are sent to output.txt by using System.setOut(fileOut). After printing a message to the file, the output is reset to the console using System.setOut(consoleOut).

Conclusion

Using the PrintStream class, redirecting System.out.println() output to a file in Java is a simple operation. Console output can be easily directed to a file by establishing a PrintStream object that points to a file and setting System.out to this PrintStream. If we need to return to console output, do not forget to restore the original System.out.