Java : GatheringByteChannel with Examples

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


Summary

A channel that can write bytes from a sequence of buffers.

Class diagram

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

try (final GatheringByteChannel channel = FileChannel.open(
        path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final ByteBuffer[] srcs = {
            ByteBuffer.wrap(new byte[]{10, 20}),
            ByteBuffer.wrap(new byte[]{30, 40, 50}),
            ByteBuffer.wrap(new byte[]{60, 70, 80, 90}),
    };

    final var ret = channel.write(srcs);
    System.out.println(ret); // 9
}

final var bytes = Files.readAllBytes(path);

// [10, 20, 30, 40, 50, 60, 70, 80, 90]
System.out.println(Arrays.toString(bytes));

Methods

long write (ByteBuffer[] srcs)

Writes a sequence of bytes to this channel from the given buffers.

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

try (final GatheringByteChannel channel = FileChannel.open(
        path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final ByteBuffer[] srcs = {
            ByteBuffer.wrap(new byte[]{10, 20}),
            ByteBuffer.wrap(new byte[]{30, 40, 50}),
            ByteBuffer.wrap(new byte[]{60, 70, 80, 90}),
    };

    final var ret = channel.write(srcs);
    System.out.println(ret); // 9
}

final var bytes = Files.readAllBytes(path);

// [10, 20, 30, 40, 50, 60, 70, 80, 90]
System.out.println(Arrays.toString(bytes));

long write (ByteBuffer[] srcs, int offset, int length)

Writes a sequence of bytes to this channel from a subsequence of the given buffers.

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

try (final GatheringByteChannel channel = FileChannel.open(
        path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final ByteBuffer[] srcs = {
            ByteBuffer.wrap(new byte[]{10}),
            ByteBuffer.wrap(new byte[]{20, 30}),
            ByteBuffer.wrap(new byte[]{40, 50, 60}),
            ByteBuffer.wrap(new byte[]{70, 80, 90, 100}),
    };

    final var ret = channel.write(srcs, 1, 2);
    System.out.println(ret); // 5
}

final var bytes = Files.readAllBytes(path);

// [20, 30, 40, 50, 60]
System.out.println(Arrays.toString(bytes));

Methods declared in Channel

close, isOpen

Please see the link below.

Methods declared in WritableByteChannel

write

Please see the link below.


Related posts

To top of page