Is it necessary to close a FileWriter, provided it is written through a BufferedWriter? [duplicate]

感情迁移 提交于 2019-12-29 06:43:08

问题


Consider a BufferedReader as below:

writer = new BufferedWriter(new FileWriter(new File("File.txt"), true));

In this case at the end of the application, I am closing the writer with writer.close()

Will this be enough? Won't that FileWriter created with new FileWriter(new File("File.txt"), true) need to be closed?


回答1:


It is not necessary to close it, because BufferedWriter takes care of closing the writer it wraps.

To convince you, this is the source code of the close method of BufferedWriter:

public void close() throws IOException {
    synchronized (lock) {
        if (out == null) {
            return;
        }
        try {
            flushBuffer();
        } finally {
            out.close();
            out = null;
            cb = null;
        }
    }
}



回答2:


It is better to close each open stream individually as all are separate stream. If there are some error occurs in nested stream, then stream won't get close. So its better to close each nested stream exclusively.

For more details refer following link:

Correct way to close nested streams and writers in Java




回答3:


Yes writer.close() closes underlying writers/streams as well.




回答4:


You need to close the outermost streams only. rest of the streams are temporary and will be closed automatically. if you create the streams separately and then nested them, in that case you need to close the individual stream. Check this Question also Correct way to close nested streams and writers in Java



来源:https://stackoverflow.com/questions/16584777/is-it-necessary-to-close-a-filewriter-provided-it-is-written-through-a-buffered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!