Java 如何使用 BufferedWriter 写入标准输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4405078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:05:04  来源:igfitidea点击:

How to write to Standard Output using BufferedWriter

java

提问by amccormack

I am currently writing an application that produces several log files using BufferedWriter. While debugging, however, I want to write to System.out instead of a file. I figured I could change from:

我目前正在编写一个使用 BufferedWriter 生成多个日志文件的应用程序。但是,在调试时,我想写入 System.out 而不是文件。我想我可以改变:

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 OutputStreamWriteroption has not been working though. How do I change just the Object inside the BufferedWriter constructor to redirect from a file to 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.

但是,新OutputStreamWriter选项并没有奏效。如何仅更改 BufferedWriter 构造函数中的对象以从文件重定向到标准输出。因为我有几个要写入的日志文件,所以在任何地方都使用 System.out 并将输出更改为文件并不是一个真正的选择。

采纳答案by Hyman

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 OutputStreamWriterand PrintWriterare Writerinstances so you can just do something like:

两个OutputStreamWriterPrintWriterWriter实例,因此你可以这样做:

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..

或者别的什么,这只是给你的想法..

回答by SBA

Since you mention that this is for logging, you might want to look at using a logger library like log4j. It'll let you change the log destination (either log file or console) by making changes in configuration files only.

由于您提到这是用于日志记录,因此您可能需要考虑使用 log4j 之类的记录器库。它可以让您通过仅更改配置文件来更改日志目标(日志文件或控制台)。