Redirecting System.out.println() Output to a File in JavaTo 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 PrintStreamThe 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
File Name: RedirectOutput.java Output: This message is back to the console. Output.txt This is a message to the file. ExplanationThe 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). ConclusionUsing 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. Next TopicAbstract-syntax-tree-vs-parse-tree |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India