问题描述
我目前正在编写一个使用BufferedWriter生成多个日志文件的应用程序。但是,在调试时,我想写入System.out而不是文件。我想我可以改变:
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:
log = new BufferedWriter(new FileWriter(tokenizerLog));
to:
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
log.write("Log output\n");
而不是:
System.out.println("log output")
新 OutputStreamWriter
选项虽然没有工作。如何仅更改BufferedWriter构造函数中的Object以从文件重定向到Standard out。因为我有几个日志文件,我将写入,在任何地方使用System.out并将输出更改为文件实际上不是一个选项。
The new OutputStreamWriter
option 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.
推荐答案
你的方法确实有效,你只是忘记刷新输出:
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();
}
两者 OutputStreamWriter
和 PrintWriter
是 Writer
个实例,所以你可以这样做:
The both OutputStreamWriter
and PrintWriter
are Writer
instances so you can just do something like:
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..
这篇关于如何使用BufferedWriter写入标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!