Java : AutoCloseable with Examples

AutoCloseable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most AutoCloseable methods.


Summary

An object that may hold resources (such as file or socket handles) until it is closed. The close() method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header.

Class diagram

class Sample implements AutoCloseable {

    @Override
    public void close() {
        System.out.println("close : called!");
    }

    public void print() {
        System.out.println("print!");
    }
}

// The close() method of an AutoCloseable object is called automatically
// when exiting a try-with-resources block. 
try (final var sample = new Sample()) {
    sample.print();
}

System.out.println("end!");

// Result
// ↓
//print!
//close : called!
//end!
try (final var sample = new Sample()) {
    throw new IllegalStateException();
} catch (IllegalStateException e) {
    System.out.println("IllegalStateException!");
}

// Result
// ↓
//close : called!
//IllegalStateException!

Methods

void close ()

Closes this resource, relinquishing any underlying resources.

final var file = Path.of("R:", "java-work", "test.txt");
System.out.println(file); // R:\java-work\test.txt

try (final var writer = Files.newBufferedWriter(file)) {
    writer.write("abcd");
}

final var str = Files.readString(file);
System.out.println(str); // abcd
final var url = URI.create("http://example.com").toURL();

try (final var reader = new BufferedReader(
        new InputStreamReader(url.openStream()))) {
    reader.lines().forEach(System.out::println);
}

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
// ...
//</html>
final var file = Path.of("R:", "java-work", "test.txt");

// An example without a try-with-resources statement.
final var writer = Files.newBufferedWriter(file);
try {
    writer.write("abcd");
} finally {
    writer.close();
}

final var str = Files.readString(file);
System.out.println(str); // abcd

Related posts

To top of page