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

谁都会走 提交于 2019-11-29 05:58:05

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;
        }
    }
}
Abhishek

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

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

Arpit

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

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