Java : GatheringByteChannel with Examples
GatheringByteChannel (Java SE 20 & JDK 20) API Examples.
You will find code examples on most GatheringByteChannel methods.
Summary
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)
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)
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));