implements Closeable or implements AutoCloseable

malas picture malas · Oct 30, 2012 · Viewed 123.5k times · Source

I'm in the process of learning Java and I cannot find any good explanation on the implements Closeable and the implements AutoCloseable interfaces.

When I implemented an interface Closeable, my Eclipse IDE created a method public void close() throws IOException.

I can close the stream using pw.close(); without the interface. But, I cannot understand how I can implement theclose() method using the interface. And, what is the purpose of this interface?

Also I would like to know: how can I check if IOstream was really closed?

I was using the basic code below

import java.io.*;

public class IOtest implements AutoCloseable {

public static void main(String[] args) throws IOException  {

    File file = new File("C:\\test.txt");
    PrintWriter pw = new PrintWriter(file);

    System.out.println("file has been created");

    pw.println("file has been created");

}

@Override
public void close() throws IOException {


}

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Oct 30, 2012

AutoCloseable (introduced in Java 7) makes it possible to use the try-with-resources idiom:

public class MyResource implements AutoCloseable {

    public void close() throws Exception {
        System.out.println("Closing!");
    }

}

Now you can say:

try (MyResource res = new MyResource()) {
    // use resource here
}

and JVM will call close() automatically for you.

Closeable is an older interface. For some reason To preserve backward compatibility, language designers decided to create a separate one. This allows not only all Closeable classes (like streams throwing IOException) to be used in try-with-resources, but also allows throwing more general checked exceptions from close().

When in doubt, use AutoCloseable, users of your class will be grateful.