Java : AutoCloseable 示例

Java 中的 AutoCloseable (Java SE 23 & JDK 23) 及其示例。
您将找到大多数 AutoCloseable 方法的代码示例。

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

可以保存资源(如文件或套接字句柄)直到关闭的对象。退出 try-with-resources 块时,将自动调用 AutoCloseable 对象的 close() 方法,该块已在资源规范标头中声明了该对象。 (机器翻译)

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

关闭此资源,放弃所有底层资源。 (机器翻译)

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

相关文章

To top of page