There are three interfaces that are quite important to the stream classes. Two are
Flushable. They are defined in java.io and were added by
JDK 5. The third,
AutoCloseable, was added by
JDK 7. It is packaged in
provides support for the try-with-resources statement, which automates the process of closing a resource. Only objects of classes that implement
can be managed by try-with-resources.
The AutoCloseable interface defines only the close( ) method:
void close( ) throws Exception
This method closes the invoking object, releasing any resources that it may hold. It is called automatically at the end of a try-with-resources statement, thus eliminating the need to explicitly call
. Because this interface is implemented by all of the
classes that open a stream, all such streams can be automatically closed by a try-with-resources statement. Automatically closing a stream ensures that it is properly closed when it is no longer needed, thus preventing memory leaks and other problems.
interface also defines the
method. Objects of a class that implement
can be closed. Beginning with
. Therefore, any class that implements
Objects of a class that implements
can force buffered output to be written to the stream to which the object is attached. It defines the
method, shown here:
void flush() throws IOException
Flushing a stream typically causes buffered output to be physically written to the underlying device. This interface is implemented by all of the
classes that write to a stream.