Will try-with-resources
call flush()
implicitly?
If it does, in the following code snippet, bw.flush()
can be safely removed?
static void printToFile1(String text, File file) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(text);
bw.flush();
} catch (IOException ex) {
// handle ex
}
}
ps. I don't see any description about it in official document:
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
close()
usually does flushing anyway. – Kissusually
works as anyone expected? – BushrangerWriter
javadoc saying that closing auto-flushes for you. The question is entirely aboutWriter
, because it is the Writer class, not the (Auto)Closeable interface, that declares theflush()
method that is the primary topic of the question, so there is no "more general" answer to the question. – Suzannsuzannaflush()
, but actually it's notWriter
that declares it either. TheWriter
-Javadoc offlush()
explicitely refers to the declaration inFlushable
. Writer only overridesflush()
. BecauseFlushable
does not extend (Auto)Closeable, its declaration cannot say anything on implementions ofclose()
. – Breccia