在 Java 中将 System.out.println() 输出重定向到文件
名为 out 的 System 类字段表示标准输出流,它是 PrintStream 类的对象。
此方法的 println() 接受任何值(任何有效的 Java 类型),打印它并终止行。
默认情况下,控制台(屏幕)是 Java 中的标准输出流(System.in),并且每当我们将任何字符串值传递给 System.out.prinln() 方法时,它都会在控制台上打印给定的字符串。
重定向 System.out.println()
Java 中 System 类的 setOut() 方法接受 PrintStream 类的一个对象,并将其设置为新的标准输出流。
因此,要将 System.out.println() 输出重定向到文件,请执行以下操作:
创建 File 类的对象。
通过将上面创建的 File 对象作为参数来实例化 PrintStream 类。
调用 System 类的 out() 方法,将 PrintStream 对象传递给它。
最后,使用 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
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP