System.out.println() is mainly used to print console messages. However, very few of us are aware of its mechanism of action.
An interesting fact regarding the above topic is that we can use System.out.println() to print messages to other sources (not just the console). However, before doing this, we need to reassign the standard output to the System class using the following method:
System.setOut(PrintStream p);
PrintStream can be used to display characters in a text file. Under program create A.txt file and save it with System.out.println (
// Java program to demonstrate redirection in System.out.println() import java.io.*; public class SystemFact { 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 System.setOut(o); System.out.println("This will be written to the text file"); // Use stored value for output stream System.setOut(console); System.out.println("This will be written on the console!"); } }
In a very similar way, we can use System.out.println() to write an OutputStream to Sockets.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.