The field named out in the System class represents a standard output Stream, which is an object of the PrintStream class .
Its println() method accepts any a value (any Java valid type), prints it and terminates the line.By default, the console (screen) is the standard output stream (System.out). in) In Java, whenever we pass any String value to System.out.prinln() method, it prints the given String on the console.
The setOut() method of the System class in java accepts an object of the PrintStream class and Set as the new standard output stream.
So, to redirect System.out.println() output to a file -
Create an object of File class.
li>Instantiate a PrintStream class by passing the File object created above as a parameter.
Call the out() method of the System class, passing
Finally, use the println() method to print the data, which will be redirected to The file represented by the File object created in the first step.
import java.io.File; import java.io.IOException; import java.io.PrintStream; public class SetOutExample { public static void main(String args[]) throws IOException { //Instantiating the File class File file = new File("D:\sample.txt"); //Instantiating the PrintStream class PrintStream stream = new PrintStream(file); System.out.println("From now on "+file.getAbsolutePath()+" will be your console"); System.setOut(stream); //Printing values to file System.out.println("Hello, how are you"); System.out.println("Welcome to Tutorialspoint"); } }
From now on D:\sample.txt will be your console
The above is the detailed content of Redirect output of System.out.println() to file in Java. For more information, please follow other related articles on the PHP Chinese website!