malas malas - 1 year ago 215
Java Question

implements Closeable or implements AutoCloseable

I'm in the process of learning Java and I cannot find any good explanation on the

implements Closeable
and the
implements AutoCloseable

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

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

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

I was using the basic code below


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");


public void close() throws IOException {


Kai Kai
Answer Source

It seems to me that you are not very familiar with interfaces. In the code you have posted you don't need to implement AutoCloseable.

You will only have to (or should) implement Closeable or AutoCloseable if you are about to implement an own PrintWriter which handles with files or any other resources which needs to be closed.

In your implementation it is enough to call pw.close(). You should do this in a finally block:

PrintWriter pw = null;
try {
   File file = new File("C:\\test.txt");
   pw = new PrintWriter(file);
} catch (IOException e) {
   System.out.println("bad things happen");
} finally {
   if (pw != null) {
      try {
      } catch (IOException e) {

The code above is Java 6 related. In Java 7 this can be done more elegant (see this answer).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download