Java : Channel with Examples

Channel (Java SE 22 & JDK 22) in Java with Examples.
You will find code samples for most of the 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.

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

Related posts

To top of page