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
Closeable
andAutoCloseable
are general-purpose interfaces that do not know anything about flushing. So you can't find any information about it in their documentation - except some words about releasing resources.A
Writer
on the other hand is a more specific-purpose abstract class that now knows something about flushing. Some excerpt of the documentation for the methodWriter.close()
:So - yes - when using a writer, a
close
will always alsoflush
. This basically means that you have to consult the documentation of the concrete classes that you are using when trying to find out what closing really does.From the Javdocs:
The
BufferedWriter.close()
explicitly stated that:The minimum amount of code to be written in this case:
Hence you don't need to call explicitly the flush method, as it will be called by the close method, as explained in the javadoc:
This behavior is inherited from the Writer class, hence besides BufferedWriter the same behavior is provided also by: CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter.
This behavior is not provided in the documentation of the tryWithResources or AutoCloseable as the behavior is specific to the given implementation of Writer. As Writerextends Closeable, it will call the close method when exiting the try {} block and the close method will first call flush as already mentioned.
The resources are automatically closed when using try-with-resource block. As part of this process it will also invoke flush automatically.
As mentioned in doc for close method of BufferedWriter:
Quoting javadoc of BufferedWriter.close():