This question already has an answer here:
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?
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;
}
}
}
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:
Yes writer.close()
closes underlying writers/streams as well.
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