【问题标题】:How do you get the text in system.output.println? [duplicate]如何获取 system.output.println 中的文本? [复制]
【发布时间】:2014-08-03 16:27:05
【问题描述】:

在我的 IDE 的输出部分(所有 system.out.println textx 出现的地方),我有几行文本。我想获取它们并将它们保存到文本文件中。可能的代码是什么?

【问题讨论】:

标签: java output


【解决方案1】:

使用System#setOut() 将输出重定向到FileOutputStream 将系统输出重定向到文件

 // for restore purpose 
 PrintStream oldOutStream = System.out;

 PrintStream outFile = new PrintStream(
            new FileOutputStream("/path/to/file.txt", true));
 System.setOut(outFile);

 System.out.println("this will goto file");

我假设您了解日志记录框架,并且您不会尝试使用它来记录某些内容

【讨论】:

    【解决方案2】:

    你可以用fileoutput strem替换所有sop并将所有内容写入文件

    如果你想写日志,那么你可以使用 log4j

    String content = "This is the content to write into file";
    
    File file = new File("filename.txt");
    
    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }
    
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 2014-06-25
      • 2010-10-17
      • 2016-07-28
      • 2021-03-24
      • 2013-04-08
      相关资源
      最近更新 更多