Java : Channel with Examples

Channel (Java SE 20 & JDK 20) API Examples.
You will find code examples on most Channel methods.


Summary

A nexus for I/O operations.

Class diagram

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

Channel channel;
try (final var fc = FileChannel.open(path,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    channel = fc;
    System.out.println(channel.isOpen()); // true
}

System.out.println(channel.isOpen()); // false

Methods

void close ()

Closes this channel.

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

Channel channel;
try (final var fc = FileChannel.open(path,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    channel = fc;
    System.out.println(channel.isOpen()); // true
}

System.out.println(channel.isOpen()); // false

An example without a try-with-resources statement.

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

final Channel channel = FileChannel.open(path,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE);
try {
    System.out.println(channel.isOpen()); // true
} finally {
    channel.close();
}

System.out.println(channel.isOpen()); // false

boolean isOpen ()

Tells whether or not this channel is open.

Please see close().


Related posts

To top of page