3月15日java学习笔记
Buffer与Channel操作
- Buffer读写流程
// 分配Buffer(容量为10)
ByteBuffer buffer = ByteBuffer.allocate(10);
// 写入数据
buffer.put((byte) 'J');
buffer.put((byte) 'A');
buffer.flip(); // 切换为读模式(position=0, limit=2)
// 读取数据
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear(); // 清空缓冲区(切换为写模式)
2. 文件Channel复制示例
try (FileChannel src = FileChannel.open(Path.of("source.txt"));
FileChannel dest = FileChannel.open(Path.of("dest.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
src.transferTo(0, src.size(), dest); // 零拷贝高效传输
}
浙公网安备 33010602011771号