Java : Closeable 示例
Closeable (Java SE 22 & JDK 22) 示例。
您将在大多数 Closeable 方法中找到代码示例。
注解 :
- 本文可能使用了翻译软件以方便阅读。 另请查看英文原文。
简介
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 示例