Java : ScatteringByteChannel with Examples
ScatteringByteChannel (Java SE 20 & JDK 20) API Examples.
You will find code examples on most ScatteringByteChannel methods.
Summary
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, 40, 50, 60, 70, 80, 90};
Files.write(path, bytes);
try (final ScatteringByteChannel channel = FileChannel.open(
path, StandardOpenOption.READ)) {
final ByteBuffer[] dsts = {
ByteBuffer.allocate(2),
ByteBuffer.allocate(3),
ByteBuffer.allocate(4),
};
final var ret = channel.read(dsts);
System.out.println(ret); // 9
System.out.println("-- dsts --");
for (final var dst : dsts) {
if (dst.hasArray()) {
System.out.println(Arrays.toString(dst.array()));
}
}
// Result
// ↓
//-- dsts --
//[10, 20]
//[30, 40, 50]
//[60, 70, 80, 90]
}
Methods
long read (ByteBuffer[] dsts)
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, 40, 50, 60, 70, 80, 90};
Files.write(path, bytes);
try (final ScatteringByteChannel channel = FileChannel.open(
path, StandardOpenOption.READ)) {
final ByteBuffer[] dsts = {
ByteBuffer.allocate(2),
ByteBuffer.allocate(3),
ByteBuffer.allocate(4),
};
final var ret = channel.read(dsts);
System.out.println(ret); // 9
System.out.println("-- dsts --");
for (final var dst : dsts) {
if (dst.hasArray()) {
System.out.println(Arrays.toString(dst.array()));
}
}
// Result
// ↓
//-- dsts --
//[10, 20]
//[30, 40, 50]
//[60, 70, 80, 90]
}
long read (ByteBuffer[] dsts, int offset, int length)
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, 40, 50, 60, 70, 80, 90};
Files.write(path, bytes);
try (final ScatteringByteChannel channel = FileChannel.open(
path, StandardOpenOption.READ)) {
final ByteBuffer[] dsts = {
ByteBuffer.allocate(1),
ByteBuffer.allocate(2),
ByteBuffer.allocate(3),
ByteBuffer.allocate(4),
ByteBuffer.allocate(5),
};
final var ret = channel.read(dsts, 1, 3);
System.out.println(ret); // 9
System.out.println("-- dsts --");
for (final var dst : dsts) {
if (dst.hasArray()) {
System.out.println(Arrays.toString(dst.array()));
}
}
// Result
// ↓
//-- dsts --
//[0]
//[10, 20]
//[30, 40, 50]
//[60, 70, 80, 90]
//[0, 0, 0, 0, 0]
}