本文介绍了如果 FileWriter 是通过 BufferedWriter 写入的,是否有必要关闭它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑如下 BufferedReader:

Consider a BufferedReader as below:

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

在这种情况下,在应用程序结束时,我使用 writer.close()

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

这就够了吗?用 new FileWriter(new File("File.txt"), true) 创建的 FileWriter 不需要关闭吗?

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

推荐答案

没有必要关闭它,因为 BufferedWriter 负责关闭它包装的 writer.

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

说服你,这是BufferedWriter的close方法的源码:

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

这篇关于如果 FileWriter 是通过 BufferedWriter 写入的,是否有必要关闭它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 08:12