将java中控制台的输出写入文本文件

Sah*_* Sj 0 java

我想在一个文本文件中显示我的Console的输出.

public static void main(String [ ] args){
    DataFilter df = new DataFilter();   
    df.displayCategorizedList();
    PrintStream out;
    try {
        out = new PrintStream(new FileOutputStream("C:\\test1.txt", true));
        System.setOut(out);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
Run Code Online (Sandbox Code Playgroud)

我在屏幕上正确得到了我的结果,但没有得到文本文件?测试文件是生成但是它是空的?

gio*_*shc 5

将系统输出流设置为文件后,应打印到"控制台".

    DataFilter df = new DataFilter();   
    PrintStream out;
    try {
        out = new PrintStream(new FileOutputStream("C:\\test1.txt", true));
        System.setOut(out);
        df.displayCategorizedList();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (out != null)
            out.close();
    }
Run Code Online (Sandbox Code Playgroud)

也可以使用finally块来始终关闭流,否则可能无法将数据刷新到文件中.