实现说明
FileChannel 散读拆帧的核心是类 FrameReader。
资源写在 try 头部,关闭由编译器生成、异常安全。
使用要点
- 直接运行文件,输出会带上标签,比如
frame length:、payload:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「FileChannel 散读拆帧」会打印什么?
整个文件跑完,输出行以 frame length:、payload: 这类前缀开头。
核心语句
channel.read(new ByteBuffer[] {lengthBuf, payload});
Path log = Files.createTempFile("frames-", ".bin");
ByteBuffer lengthBuf = ByteBuffer.allocate(4);
代码示例
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);
}
}