📌  相关文章
📜  将 System.out.println() 输出重定向到Java中的文件

📅  最后修改于: 2022-05-13 01:55:51.189000             🧑  作者: Mango

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

System.out.println()主要用于将消息打印到控制台。然而,我们中很少有人真正意识到它的工作机制。我们也可以使用System.out.println()将消息打印到其他来源,而不仅仅是将其限制在控制台。但是,在这样做之前,我们必须使用 System 类的以下方法重新分配标准输出,如下所示:

句法:

System.setOut(PrintStream p);
  • SystemJava.lang包中定义的一个类。
  • out 是PrintStream的一个实例,它是System类的公共静态成员。
  • 由于PrintStream类的所有实例都有一个公共方法println() ,因此我们也可以在 out 上调用相同的方法。我们可以假设System.out代表标准输出流。

程序:

  1. 创建文件类对象
  2. 通过传递上面的 Fiel 类的对象作为参数来实例化 PrintStream 类。
  3. 通过提供 PrintStream 对象调用 System 类的 out() 方法。
  4. 最后,使用 print() 方法打印数据。

示例输入文件如下:

例子:

Java
// Java Program to Demonstrate Redirection in
// System.out.println() By Creating .txt File
// and Writing to the file Using
// System.out.println()
 
// Importing required classes
import java.io.*;
 
// Main class
// SystemFact
public class GFG {
 
    // Main driver method
    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
        // using setOut() method
        System.setOut(o);
 
        // Display message only
        System.out.println(
            "This will be written to the text file");
 
        // Use stored value for output stream
        System.setOut(console);
 
        // Display message only
        System.out.println(
            "This will be written on the console!");
    }
}


输出: