Java Streams

While developing a Java application I've been working on, I had some problems using Streams. The code compiled and ran OK and there were no errors, but the result was not what I hoped for.

The code reads an input file, does some string manipulations, and writes to an output file. This it did. But the resulting output file was not complete, being shorter than it should have been. I remembered some example code that I had experimented with in the past that did not have this problem. I compared the working code against mine. A noticable difference was that the example code had close() lines for the streams. My intuition was that Java would close the streams when they were no longer needed via GC, but I saw no harm in explicitly closing them when I knew they were no longer needed, and in fact thought it to be a "best practice", so I tried it. Amazingly enough, that solved the problem. It seems that Java was closing the streams before they were no longer needed.

My code has a FileInputStream "fis" that is wrapped inside a InputStreamReader "isr" which in turn is wrapped in a BufferedReader "br". So I closed them in the order I had instantiated them, innermost first, like so

fis.close();
isr.close();
br.close();

After the string manipulations, the code similarly has a FileOutputStream "fos" wrapped in an OutputStreamWriter "osw" that is wrapped in a BufferedWriter "bw". But when I closed them like

fos.close();
osw.close();
bw.close();

I got – IOException: Stream closed

For some reason, they have to be closed outermost first. I still don't thoroughly understand exactly why, but I can sense it has to do with the writing as opposed to reading.

I also experienced stream problems with some code using the JPEG codec. I was getting – TruncatedFileException: Premature end of input file

Without any close() lines, the code didn't work. With them it worked better, but with the Exception. But after adding flush() lines to the code, also outermost first as it is writing, the problem was solved.

Technorati Tags:

Post a Comment

Your email is never shared. Required fields are marked *

*
*