【问题标题】:How to save output in console display to a text file in Java?如何将控制台显示中的输出保存到 Java 中的文本文件中?
【发布时间】:2021-07-02 08:53:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: java console text-files


    【解决方案1】:

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

    
            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");
    
    

    【讨论】:

    • 非常感谢您的回答!但是我认为在输出很多的情况下不好:(
    • 这是否解决了您的问题,如果是,请接受答案并点击投票
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2011-10-29
      相关资源
      最近更新 更多