Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to Standard Output using BufferedWriter

Tags:

java

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.

like image 970
amccormack Avatar asked Dec 10 '10 02:12

amccormack


People also ask

What type of value does the BufferedWriter method write () return?

Return value: This method does not return any value.

Why BufferedWriter is not writing to the file?

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.

Does BufferedWriter write new line?

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.


2 Answers

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

like image 187
Jack Avatar answered Sep 18 '22 20:09

Jack


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.

like image 25
SBA Avatar answered Sep 18 '22 20:09

SBA