【问题标题】:Writing output from console in java to text file将Java中控制台的输出写入文本文件
【发布时间】:2013-04-05 07:24:16
【问题描述】:

我想在一个文本文件中显示我的控制台输出。

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

}

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

【问题讨论】:

  • df.displayCategorizedList(); 是否打印到标准输出?那你应该把它移到System.setOut()
  • 我是java新手,请给我更多提示
  • 这个话题似乎处理得相当彻底over here
  • @SaharSj 他的意思是输出好像在你调用setOut()之前就已经完成了。只需将 df.displayCategorizedList(); 移到 try/catch 块下方即可。

标签: java


【解决方案1】:

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

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

还可以使用 finally 块来始终关闭流,否则数据可能不会刷新到文件中。

【讨论】:

  • 你将o/p流设置为文件然后保存在c文件夹中
【解决方案2】:

我会建议以下方法:

public static void main(String [ ] args){
    DataFilter df = new DataFilter();   
    try (PrintStream out = new PrintStream(new FileOutputStream("d:\\file.txt", true))) {
          System.setOut(out);
          df.displayCategorizedList();
    } catch (FileNotFoundException e) {
        System.err.println(String.format("An error %s occurred!", e.getMessage()));
    }
}

这是使用 JDK 7 的 try-with-resources 功能 - 这意味着它会处理您拥有的异常(如 FileNotFoundException),并且还会关闭资源(而不是 finally 块)。

如果您不能使用 JDK 7,请使用其他回复中建议的方法之一。

【讨论】: