Java : WritableByteChannel with Examples

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


Summary

A channel that can write bytes.

Class diagram

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

try (final WritableByteChannel channel = Files.newByteChannel(path,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final byte[] bytes = {10, 20, 30, 40, 50};
    final var src = ByteBuffer.wrap(bytes);

    src.limit(3);

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

    final var ret = channel.write(src);
    System.out.println(ret); // 3

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

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

Methods

int write (ByteBuffer src)

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

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

try (final WritableByteChannel channel = Files.newByteChannel(path,
        StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    final byte[] bytes = {10, 20, 30, 40, 50};
    final var src = ByteBuffer.wrap(bytes);

    src.limit(3);

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

    final var ret = channel.write(src);
    System.out.println(ret); // 3

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

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

Methods declared in Channel

close, isOpen

Please see the link below.


Related posts

To top of page