Is flush() call necessary when using try-with-resources
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:
Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.
Closeable
and AutoCloseable
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 method Writer.close()
:
Closes the stream, flushing it first.
So - yes - when using a writer, a close
will always also flush
. 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.