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 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.
Return value: This method does not return any value.
You're creating a new FileWriter each time through the loop, which will truncate the file each time. BufferedWriter is buffered, and you're never flushing the buffer. You need to either call bw. flush(), or even better, close the writer when done.
The newLine() method of BufferedWriter class in Java is used to separate the next line as a new line. It is used as a write separator in buffered writer stream.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With