Java : ReadableByteChannel with Examples

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


Summary

A channel that can read bytes.

Class diagram

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

final byte[] bytes = {10, 20, 30};
Files.write(path, bytes);

try (final ReadableByteChannel channel =
             Files.newByteChannel(path, StandardOpenOption.READ)) {

    final var dst = ByteBuffer.allocate(5);
    System.out.println(dst); // java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
    if (dst.hasArray()) {
        System.out.println(Arrays.toString(dst.array())); // [0, 0, 0, 0, 0]
    }

    final var ret = channel.read(dst);
    System.out.println(ret); // 3

    System.out.println(dst); // java.nio.HeapByteBuffer[pos=3 lim=5 cap=5]
    if (dst.hasArray()) {
        System.out.println(Arrays.toString(dst.array())); // [10, 20, 30, 0, 0]
    }
}

Methods

int read (ByteBuffer dst)

Reads a sequence of bytes from this channel into the given buffer.

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

final byte[] bytes = {10, 20, 30};
Files.write(path, bytes);

try (final ReadableByteChannel channel =
             Files.newByteChannel(path, StandardOpenOption.READ)) {

    final var dst = ByteBuffer.allocate(5);
    System.out.println(dst); // java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
    if (dst.hasArray()) {
        System.out.println(Arrays.toString(dst.array())); // [0, 0, 0, 0, 0]
    }

    final var ret = channel.read(dst);
    System.out.println(ret); // 3

    System.out.println(dst); // java.nio.HeapByteBuffer[pos=3 lim=5 cap=5]
    if (dst.hasArray()) {
        System.out.println(Arrays.toString(dst.array())); // [10, 20, 30, 0, 0]
    }
}

Methods declared in Channel

close, isOpen

Please see the link below.


Related posts

To top of page