![]() |
VOOZH | about |
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.
System.setOut(PrintStream p);
Note:PrintStream can be used for character output to a text file.
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()
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.