Java : ByteChannel with Examples

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


Summary

A channel that can read and write bytes. This interface simply unifies ReadableByteChannel and WritableByteChannel; it does not specify any new operations.

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 ByteChannel channel = Files.newByteChannel(path,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.READ)) {

    final var array = new byte[5];

    final var buffer = ByteBuffer.wrap(array);
    System.out.println(buffer); // java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]

    System.out.println(buffer.position()); // 0
    System.out.println(Arrays.toString(array)); // [0, 0, 0, 0, 0]

    final var ret1 = channel.read(buffer);
    System.out.println(ret1); // 3

    System.out.println(buffer.position()); // 3
    System.out.println(Arrays.toString(array)); // [10, 20, 30, 0, 0]

    buffer.put(3, (byte) 40);
    buffer.put(4, (byte) 50);

    System.out.println(buffer.position()); // 3
    System.out.println(Arrays.toString(array)); // [10, 20, 30, 40, 50]

    final var ret2 = channel.write(buffer);
    System.out.println(ret2); // 2

    System.out.println(buffer.position()); // 5
}

final var ret = Files.readAllBytes(path);
System.out.println(Arrays.toString(ret)); // [10, 20, 30, 40, 50]

Methods declared in Channel

close, isOpen

Please see the link below.

Methods declared in ReadableByteChannel

read

Please see the link below.

Methods declared in WritableByteChannel

write

Please see the link below.


Related posts

To top of page