Java : AutoCloseable con ejemplos

AutoCloseable (Java SE 23 & JDK 23) en Java con ejemplos.
Encontrará muestras de código para la mayoría de los métodos AutoCloseable.

Nota :


Summary

Un objeto que puede contener recursos (como identificadores de archivos o sockets) hasta su cierre. El método close() de un objeto AutoCloseable se llama automáticamente al salir de un bloque try-with-resources para el que se declaró el objeto en la cabecera de especificación de recursos. (Traducción automática)

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 ()

Cierra este recurso, renunciando a cualquier recurso subyacente. (Traducción automática)

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