Course contentsShow
← Java
Lesson 1946 of 2,87039. File I/O: Basic Byte StreamsFree lesson

AutoCloseable and Closeable Interfaces

How streams implement AutoCloseable, enabling try-with-resources and defining the close contract.

AutoCloseable and Closeable Interfaces

You'll learn: How streams implement AutoCloseable, enabling try-with-resources and defining the close contract.

The Core Idea

When you use try-with-resources (as you learned in the previous lesson), Java automatically calls close() on your streams. But how does Java know an object can be closed? The answer: interfaces.

Java defines two key interfaces:

  • AutoCloseable (introduced in Java 7) — the broadest contract, used by try-with-resources
  • Closeable (older, from Java 5) — extends AutoCloseable, specifically for I/O streams

Any class implementing AutoCloseable can be used in a try-with-resources statement. The interface requires exactly one method:

void close() throws Exception

Closeable is more specific for I/O operations and narrows the exception type:

void close() throws IOException

Why This Matters for Streams

All stream classes (FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream) implement Closeable, which means they also implement AutoCloseable. This is the contract that makes try-with-resources work:

try (FileInputStream fis = new FileInputStream("data.bin")) {
    // Java knows it can auto-close fis because FileInputStream implements Closeable
}

Analogy: Think of AutoCloseable as a "promise badge" an object wears. When Java sees that badge in a try-with-resources statement, it knows: "I promise to clean up after myself when this block ends."

The Close Contract

Implementing these interfaces means guaranteeing:

  • Resources are released when close() is called
  • Calling close() multiple times is safe (idempotent)
  • After closing, the stream should not be used

Key Takeaway: AutoCloseable and Closeable are the interfaces that make try-with-resources possible; all Java I/O streams implement Closeable, promising they can be safely and automatically closed.