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");
as opposed to:
System.out.println("log output")
The new OutputStreamWrite开发者_开发百科r
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();
}
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..
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.
精彩评论