问题
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