Java Redirect System.out to a different location with BufferedOutputStream issue solved

I have been architect and developing an automation framework recently. And I have been coding  the framework in a pair with a colleague. We need to print out the result of the of test. He used System.out.println() in many different locations in the code to print result to the console, and then he decided to save the result in a different file instead. So he decided to use System.setOut() method came with System class.

Here is the code for setting up:

Code snippet #1:

System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(testResultsLocation))));

Code snippet #2:

System.out.println();

Since there are a lot result data to be written to the file, when the framework is run, we find that part of the results are missing from the file. I looked at closely the result file, and found they appear to be cutoff.

From the past experience, I had a feeling there must be something being left behind in the stream/buffer or it has to do with buffer size.

So I tried increasing the buffer size for Buffer like so:

System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(testResultsLocation), 100000)));

It didn’t solve the problem, it made it worse, more lines are missing. This leads me to conclude it has to do with things left over in the buffer. I look at the code further, I found there were no flush is done.

So I aded:

System.out.flush();

after

System.out.println();

This solves the problem, and all my results are back into the file. To conclude, if the buffer is not full, nothing will be written out, which leads to the mssing lines; We need to remember flush the stream to have the content written to the file we want.

After fixing the problem, I thought further, and I felt that there is no point to use a BufferedFileOutput anyways, without the buffer, things will be written directly to the file, so nothing will be left behind. To test, I changed the setup line to:

System.setOut(new PrintStream(new FileOutputStream(testResultsLocation)));

And without adding the System.out.flush() line at all, the problem is also solved.

Alternatively (I did not test it), I think one can set a very small buffer (ex. 1) so as long as there is a line, it will be written out to the file.

 

Leave a Reply

Your email address will not be published. Required fields are marked *