Home > Java > javaTutorial > Redirect output of System.out.println() to file in Java

Redirect output of System.out.println() to file in Java

王林
Release: 2023-09-06 08:09:04
forward
867 people have browsed it

在Java中将System.out.println()的输出重定向到文件

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.

Redirect System.out.println()

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.

Example

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");
   }
}
Copy after login

Output

From now on D:\sample.txt will be your console
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template