FileChannel Scatter Read Framing
FileChannel.read into a ByteBuffer array scatters bytes across buffers in order, letting one call fill a length field and its payload without copying.
Code
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class FrameReader {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("frames-", ".bin");
// Frame format: 4-byte big-endian length + payload; the file holds "hello" and "bye" frames
Files.write(log, new byte[] {0, 0, 0, 5, 'h', 'e', 'l', 'l', 'o',
0, 0, 0, 3, 'b', 'y', 'e'});
try (FileChannel channel = FileChannel.open(log, StandardOpenOption.READ)) {
// Scattering read: one call fills the two buffers in sequence
ByteBuffer lengthBuf = ByteBuffer.allocate(4);
ByteBuffer payload = ByteBuffer.allocate(5);
channel.read(new ByteBuffer[] {lengthBuf, payload});
lengthBuf.flip();
payload.flip();
System.out.println("frame length: " + lengthBuf.getInt());
System.out.println("payload: " + new String(payload.array(), 0, payload.limit()));
}
Files.deleteIfExists(log);
}
}Inside the snippet
The working surface is the class FrameReader — everything else is wiring.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Putting it to use
The demo output is labeled (frame length:, payload:), so every printed line maps back to its originating operation.
Core lines
channel.read(new ByteBuffer[] {lengthBuf, payload});
Path log = Files.createTempFile("frames-", ".bin");
ByteBuffer lengthBuf = ByteBuffer.allocate(4);
Interactive Tools for This Topic
FAQ
- What does FileChannel Scatter Read Framing print when run?
- Execute the whole file; each printed line is prefixed with a label like `frame length:`, `payload:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.