Closeable Flushable Java

Closeable and Flushable interfaces were introduced with JDK 1.5 version and part of package.

1. Closeable interface (of Closeable Flushable Java)

The Closeable interface includes only one abstract method, close(). When close() method is called, the system resources held by the stream object are released and can be used by other part of the program (avoids memory leaks). Many stream classes implement this interface and overrides the close() method. Any class that implements this interface can use close() method to close the stream handle. Also if the super class implements this interface, the sub class can use this method. For example, the InputStream implements this method and its subclass FileInputStream can use close() method. For that matter, all the streams can use close() method as the super classes of all streams, InputStream, OutputStream, Reader and Writer, implement Closeable interface.

2. Flushable interface (of Closeable Flushable Java)

The Flushable interface includes only one method – flush(). Many destination streams implement this interface and overrides the flush() method. When this method is called, the data held in the buffers is flushed out to the destination file to write.

Following are a few classes ' signature that implements Closeable Flushable Java (either one or both)

public abstract class InputStream extends Object implements Closeable
public abstract class OutputStream extends Object implements Closeable, Flushable
public abstract class Reader extends Object implements Readable, Closeable
public abstract class Writer extends Object implements Appendable, Closeable, Flushable
public class PrintStream extends FilterOutputStream implements Appendable, Closeable

The close() and flush() methods throw a checked exception IOException and must be handled when these methods are used.

Leave a Comment

Your email address will not be published.