简体   繁体   English

如何使用BufferedWriter写入标准输出

[英]How to write to Standard Output using BufferedWriter

I am currently writing an application that produces several log files using BufferedWriter. 我目前正在编写一个使用BufferedWriter生成多个日志文件的应用程序。 While debugging, however, I want to write to System.out instead of a file. 但是,在调试时,我想写入System.out而不是文件。 I figured I could change from: 我想我可以改变:

log = new BufferedWriter(new FileWriter(tokenizerLog));

to: 至:

BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
log.write("Log output\n");

as opposed to: 而不是:

System.out.println("log output")

The new OutputStreamWriter option has not been working though. 新的OutputStreamWriter选项尚未运行。 How do I change just the Object inside the BufferedWriter constructor to redirect from a file to Standard out. 如何只更改BufferedWriter构造函数中的Object以从文件重定向到Standard out。 Because I have several log files I will be writing to, using System.out everywhere and changing the output to a file isn't really an option. 因为我有几个日志文件,我将写入,使用System.out无处不在,并将输出更改为文件实际上不是一个选项。

Your approach does work, you are just forgetting to flush the output: 您的方法确实有效,您只是忘记刷新输出:

try {    
  BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));

  log.write("This will be printed on stdout!\n");
  log.flush();
}
catch (Exception e) {
  e.printStackTrace();
}

The both OutputStreamWriter and PrintWriter are Writer instances so you can just do something like: OutputStreamWriterPrintWriter都是Writer实例,因此您可以执行以下操作:

BufferedWriter log;

Writer openForFile(String fileName) {
  if (fileName != null)
    return new PrintWriter(fileName);
  else
    return new OutputStreamWriter(System.out);
}

log = new BufferedWriter(openForFile(null)); //stdout
log = new BufferedWriter(openForFile("mylog.log")); // using a file

or whatever, it is just to give you the idea.. 或者其他什么,它只是给你一个想法..

Since you mention that this is for logging, you might want to look at using a logger library like log4j. 由于您提到这是用于日志记录,您可能希望查看使用log4j之类的记录器库。 It'll let you change the log destination (either log file or console) by making changes in configuration files only. 它允许您通过仅更改配置文件来更改日志目标(日志文件或控制台)。

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

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