我应该按照什么顺序关闭缓冲区写入程序和文件写入程序



我知道BufferedWriter.close会自动关闭底层的filewriter源。但出于某种原因,我被赋予了一项任务,这两项任务都需要完成。到目前为止,我一直按照这个顺序做,

filewriter.close();

bufferwriteer.close();

这个命令对我来说是正确的。然而,另一种方式,

bufferedwriter.close();

filewriter.close();

在这里,它是否会抛出一个空指针,因为filewriter已经关闭了?正确的顺序是什么?同样的道理也适用于bufferedreader和filereader吗?

bufferedwriter.close();
filewriter.close();

这不会引发null指针异常。您可能会认为这是因为BufferedWriterclose()方法将Writer字段设置为null,但由于Java按值传递对象引用,因此原始的FileWriter仍然不是null。关闭它不会有任何效果。

这是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;
        }
    }
}

来自FileWriter继承的OutputStreamWriter.close()文档。

关闭流,先冲洗它。流关闭后,进一步的write()或flush()调用将引发IOException。关闭以前关闭的流没有任何效果。

因此,关闭一个已经被BufferedWriter关闭的FileWriter应该很好。

更多信息:http://docs.oracle.com/javase/7/docs/api/java/io/OutputStreamWriter.html

最新更新