2

I know that BufferedWriter.close would automatically close the underlying filewriter source. But for some reason I have been given the task which requires closing both. So far I have been doing it in this order,

filewriter.close();

bufferwriter.close();

This order to me feels correct. The other way however,

bufferedwriter.close();

filewriter.close();

here, wont it throw a null pointer since the filewriter would already be closed? What is the correct order ? Also does the same apply to bufferedreader and filereader ?

happyHelper
  • 119
  • 8
  • This is not a duplicate I am asking only because I did go through the existing solutions and couldnt find a satisfactory response. – happyHelper Apr 03 '15 at 16:08

2 Answers2

3
bufferedwriter.close();

filewriter.close();

This will not throw a null pointer exception. You may be thinking it would because the close() method of BufferedWriter sets the Writer field to null, but because Java passes object references by value, the original FileWriter is still not null. Closing it won't have any effect.

This is the implementation of BufferedWriter#close():

public void close() throws IOException {
    synchronized (lock) {
        if (out == null) {
            return;
        }
        try {
            flushBuffer();
        } finally {
            out.close();  // this closes the FileWriter
            out = null;   // the original FileWriter passed to the BufferedWriter is still not null after this call
            cb = null;
        }
    }
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • And the same applies for bufferedreader and filereader as well, i assume ? – happyHelper Apr 03 '15 at 16:10
  • Also just out of curiosity, what would happen if I close filewriter.close() and then bufferdwriter.close(); wouldnt it have the same effect ? – happyHelper Apr 03 '15 at 16:20
  • 1
    @happyHelper Same for `BufferedReader`. And for the ordering difference, I suggest you check http://stackoverflow.com/questions/6586866/closing-nested-streams and http://stackoverflow.com/questions/884007/best-way-to-close-nested-streams-in-java-6. – M A Apr 03 '15 at 16:29
3

From the OutputStreamWriter.close() documentation that FileWriter inherits.

Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.

So you should be fine closing a FileWriter that was already closed by the BufferedWriter.

More information: http://docs.oracle.com/javase/7/docs/api/java/io/OutputStreamWriter.html

Curtis
  • 681
  • 4
  • 9