2.3 ByteBuffer 常见方法

简介: 2.3 ByteBuffer 常见方法

可以使用 allocate 方法为 ByteBuffer 分配空间,其它 buffer 类也有该方法

Bytebuffer buf = ByteBuffer.allocate(16);

向 buffer 写入数据

有两种办法

  • 调用 channel 的 read 方法
  • 调用 buffer 自己的 put 方法

int readBytes = channel.read(buf);

buf.put((byte)127);

从 buffer 读取数据

  • 调用 channel 的 write 方法
  • 调用 buffer 自己的 get 方法

int writeBytes = channel.write(buf);

byte b = buf.get();

get 方法会让 position 读指针向后走,如果想重复读取数据

  • 可以调用 rewind 方法将 position 重新置为 0
  • 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针


目录
相关文章
|
8月前
2. ByteBuffer
2. ByteBuffer
21 0
|
8月前
2.1 ByteBuffer 正确使用姿势
2.1 ByteBuffer 正确使用姿势
38 0
|
8月前
|
存储
ByteBuffer 大小分配
ByteBuffer 大小分配
53 0
|
10月前
|
存储 Java 容器
|
10月前
|
存储 Java
NIO之Buffer解读(下)
NIO之Buffer解读(下)
|
12月前
|
算法 Java 索引
ByteBuffer
ByteBuffer
51 0
|
存储 消息中间件 缓存
ByteBuffer总结
ByteBuffer总结
|
Java
|
Java 测试技术 容器
NIO 下的 ByteBuffer简单学习
NIO 下的 ByteBuffer简单学习
99 0
|
Java API 索引
ByteBuf 和 ByteBuffer 的区别, ByteBuf 动态扩容源码分析
ByteBuf 和 ByteBuffer 的区别, ByteBuf 动态扩容源码分析
426 0