Java : Closeable with Examples

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


Summary

A Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding (such as open files).

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

Closes this stream and releases any system resources associated with it.

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]

Related posts

To top of page