Java : ScatteringByteChannel con ejemplos
ScatteringByteChannel (Java SE 24 & JDK 24) en Java con ejemplos.
Encontrará muestras de código para la mayoría de los métodos ScatteringByteChannel.
Nota :
- Este artículo puede utilizar software de traducción para su comodidad. Consulte también la versión original en inglés.
Summary
Un canal que puede leer bytes en una secuencia de buffers. (Traducción automática)
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)
Lee una secuencia de bytes de este canal en los buffers indicados. (Traducción automática)
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)
Lee una secuencia de bytes de este canal en una subsecuencia de los buffers dados. (Traducción automática)
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]
}