繁体   English   中英

如何将控制台显示中的输出保存到 Java 中的文本文件?

[英]How to save output in console display to a text file in Java?

我尝试使用以下代码将应用程序的输出保存到文本文件中。 它可以将输出写入文本文件,但输出未显示在控制台显示中。 我该如何处理控制台上显示的输出并保存到文件?

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class DocGhiFile {
    public static void main(String[] args) {

        try {
            final boolean append = true, autoflush = true;
            PrintStream printStream = new PrintStream(new FileOutputStream("test.txt", append), autoflush);
            System.setOut(printStream);
            System.setErr(printStream);

        } catch (IOException e) {
            System.out.println("Error during reading/writing");
        }
        System.out.println("TEST");
    }
}

代码运行后控制台显示和文本文件:

使用两个打印流,一个写入控制台,另一个写入文件,如下所示


        try {
            final boolean append = true, autoflush = true;
            PrintStream printWriter = new PrintStream(new FileOutputStream("test.txt", append), autoflush);
            PrintStream printStream = new PrintStream(System.out, autoflush); // to write to console
            System.setOut(printWriter);
            printStream.println("Test to console");
            System.setErr(printWriter);

        } catch (IOException e) {
            System.out.println("Error during reading/writing");
        }
        System.out.println("TEST to file");

您实际上可以在command prompt运行您的Java Program ,以save您的Program OutputConsole Output

java Programfile | (管道) clipboard :将您的程序输出保存到剪贴板。

java Programfile > Sourcefile将您的程序输出写入源文件。

java Programfile >> Sourcefile将您的程序输出附加到源文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM