Java 如果 FileWriter 是通过 BufferedWriter 写入的,是否有必要关闭它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16584777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
提问by vivek_jonam
Consider a BufferedReader as below:
考虑一个 BufferedReader 如下:
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()
在这种情况下,在应用程序的结束,我关闭writer
与writer.close()
Will this be enough? Won't that FileWriter created with new FileWriter(new File("File.txt"), true)
need to be closed?
这够了吗?创建的 FileWriternew FileWriter(new File("File.txt"), true)
不需要关闭吗?
采纳答案by sambe
It is not necessary to close it, because BufferedWriter takes care of closing the writer it wraps.
没有必要关闭它,因为 BufferedWriter 负责关闭它包装的编写器。
To convince you, this is the source code of the close method of BufferedWriter:
说服你,这是BufferedWriter的close方法的源码:
public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try {
flushBuffer();
} finally {
out.close();
out = null;
cb = null;
}
}
}
回答by harsh
Yes writer.close()
closes underlying writers/streams as well.
Yeswriter.close()
也会关闭底层的 writers/streams。
回答by 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:
更多详情请参考以下链接:
回答by 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
您只需要关闭最外面的流。其余的流是临时的,将自动关闭。如果您单独创建流然后嵌套它们,在这种情况下您需要关闭单个流。检查这个问题也是在 Java 中关闭嵌套流和编写器的正确方法