ByteBuffer 用法详解

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值