ByteBuffer 是 Java NIO 中用于处理字节数据的关键类,提供了比传统 byte[] 更灵活和高效的字节操作方式。以下是 ByteBuffer 的主要用法:
基础
1. 创建 ByteBuffer
分配新缓冲区
// 分配堆内存缓冲区 (在JVM堆上)
ByteBuffer heapBuffer = ByteBuffer.allocate(1024);
// 分配直接内存缓冲区 (在操作系统内存中)
ByteBuffer directBuffer = ByteBuffer.allocateDirect(1024);
直接缓冲区(allocateDirect)性能更高但分配成本较大,适合长期使用或大缓冲区
包装现有数组
byte[] byteArray = new byte[1024];
ByteBuffer wrappedBuffer = ByteBuffer.wrap(byteArray);
// 可以指定起始位置和长度
ByteBuffer slicedBuffer = ByteBuffer.wrap(byteArray, 100, 200);
2. 核心属性
ByteBuffer 有四个核心属性:
- capacity: 缓冲区容量(创建后不可变)
- position: 当前读写位置
- limit: 可读写边界
- mark:标记位置(用于reset)
position 和 limit 的关系:
写模式:position 表示下一个写入位置,limit 表示容量
读模式:position 表示下一个读取位置,limit 表示可读上限
ByteBuffer buffer = ByteBuffer.allocate(10);
System.out.println("capacity: " + buffer.capacity()); // 10
System.out.println("position: " + buffer.position()); // 0
System.out.println("limit: " + buffer.limit()); // 10
3. 基本读写操作
写入数据
buffer.put((byte)1); // 写入单个字节
buffer.put(new byte[]{
2,3,4}); // 写入字节数组
buffer.putInt(12345); // 写入int(4字节)
buffer.putLong(123456789); // 写入long(8字节)
buffer.putDouble(3.14); // 写入double(8字节)
读取数据
byte b = buffer.get(); // 读取单个字节
byte[] dst = new byte[3];
buffer.get(dst); // 读取到字节数组
int i = buffer.getInt(); // 读取int
long l = buffer.