Java : Closeable 示例

Closeable (Java SE 22 & JDK 22) 示例。
您将在大多数 Closeable 方法中找到代码示例。

注解 :

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

简介

Closeable 是可以关闭的数据源或目标。调用 close 方法来释放对象所持有的资源(例如打开的文件)。 (机器翻译)

Class diagram

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

// I recommend to use a try-with-resources statement.
try (final var writer = Files.newBufferedWriter(path)) {

    writer.write("abcd");
    writer.newLine();

    writer.write("XYZ");
    writer.newLine();
}

final var str = Files.readString(path);
System.out.print(str);

// Result
// ↓
//abcd
//XYZ

Methods

void close ()

关闭此流并释放与其相关的所有系统资源。 (机器翻译)

final var path = Path.of("R:", "java-work", "aaa.data");
System.out.println(path); // R:\java-work\aaa.data

try (final var outputStream = Files.newOutputStream(path)) {
    outputStream.write(10);
    outputStream.write(20);
    outputStream.write(30);
}

final var bytes = Files.readAllBytes(path);
System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
// An example without a try-with-resources statement.
final var path = Path.of("R:", "java-work", "aaa.data");
System.out.println(path); // R:\java-work\aaa.data

final var outputStream = Files.newOutputStream(path);
try {
    outputStream.write(10);
    outputStream.write(20);
    outputStream.write(30);
} finally {
    outputStream.close();
}

final var bytes = Files.readAllBytes(path);
System.out.println(Arrays.toString(bytes)); // [10, 20, 30]

相关文章

  • API 示例
To top of page