Saturday, August 17, 2013

Java: File and Buffered Reader/Writer

Well, this is kind of logical situation, but I thought it should not matter since all of them would be closed anyway. Here's the story:

So my task was to build a Java application which would accept commands and ultimately you want to record everything that you have done in a text file (you could also open the file to continue the work). Without hesitation, I looked at an old code that has text file reading function (written by my Prof. of course as a template to do tutorial), thus I decided to use FileReader and BufferedReader instead of other methods available around. Logically, I looked up into FileWriter and BufferedWriter, and both of them do exist.

Here comes my stupidity: I close the FileWriter before the BufferedWriter. I thought it was fine, since that was what happened in some old template code given to me (for reader and not writer). The problem was, in those codes, the reader was only called once for every program execution. In my case, I repeatedly call FileWriter and BufferedWriter for every operation that changes the text file as a risk mitigation in case my program crashes due to invalid and error-causing input or the computer crashes. And that, somehow somewhat, makes closing BufferedWriter before FileWriter important! Otherwise, I would get run time error and my text file would just be reset into empty forever and ever.

So folks, remember to close what's opened last before closing what's opened first (like chestception where you would need to close the innermost chest first before closing the outermost one).

No comments:

Post a Comment