There are three interfaces that are quite important to the stream classes. Two are
Closeable and 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 java.lang .
AutoCloseable provides support for the try-with-resources statement, which automates the process of closing a resource. Only objects of classes that implement AutoCloseable can be managed by try-with-resources.The AutoCloseable interface defines only the close( ) method: void close( ) throws Exception close() . Because this interface is implemented by all of the I/O 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.The Closeable interface also defines the close() method. Objects of a class that implement Closeable can be closed. Beginning with JDK 7 , Closeable extends AutoCloseable . Therefore, any class that implements Closeable also implements AutoCloseable .Objects of a class that implements Flushable can force buffered output to be written to the stream to which the object is attached. It defines the flush() 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 I/O classes that write to a stream.
|