PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

王林
王林 转载
2023-09-06 08:09:04 365浏览

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

System类中名为out的字段表示一个标准输出Stream,是PrintStream类的一个对象。

它的 println() 方法接受任何 a 值(任何 Java 有效类型),打印它并终止该行。

默认情况下,控制台(屏幕)是标准输出流(System.out)。 in) 在 Java 中,每当我们将任何 String 值传递给 System.out.prinln() 方法时,它都会在控制台上打印给定的 String。

重定向 System.out.println()

java中System类的setOut()方法接受PrintStream类的对象并将其设置为新的标准输出流。

因此,要将 System.out.println() 输出重定向到文件 -

  • 创建 File 类的对象。

    li>
  • 通过将上面创建的 File 对象作为参数传递来实例化一个 PrintStream 类。

  • 调用 System 类的 out() 方法,传递

  • 最后,使用 println() 方法打印数据,它将被重定向到第一步创建的 File 对象表示的文件。

示例

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

以上就是在Java中将System.out.println()的输出重定向到文件的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除