9、ByteBuffer(方法演示3(buffer4种读取数据方式))

ByteBuffer(方法演示3(buffer4种读取数据方式))

buffer读取数据方式1、(buffer.get(一位一位的读,不能重复读))

 

Buffer读取数据方式2、(buffer.rewind(可以重复读(重头开始读,源码就是将positon设为了0)))

 

 

这里重头开始读一位(所以就是0号的a了)

 

Buffer读取数据方式3、(mark&reset(算是对前面的rewind的增强吧))

 

测试:

 

Buffer读取数据方式4、(get(i)就是读取位置的字符,不会改变position位置)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个示例代码,演示了如何使用 `ByteBuffer` 进行紧凑化(compact)操作,并继续向其写入数据,然后读取数据: ```java import java.nio.ByteBuffer; public class ByteBufferExample { public static void main(String[] args) { // 创建一个容量为 10 的 ByteBuffer ByteBuffer buffer = ByteBuffer.allocate(10); // 向 ByteBuffer 写入数据 buffer.put((byte) 'H') .put((byte) 'e') .put((byte) 'l') .put((byte) 'l') .put((byte) 'o'); // 输出当前 ByteBuffer 的内容 System.out.println("Current position: " + buffer.position()); System.out.println("Current limit: " + buffer.limit()); System.out.println("Current content: " + new String(buffer.array())); // 紧凑化 ByteBuffer System.out.println("Compact the buffer"); buffer.compact(); // 输出紧凑化之后的 ByteBuffer 信息 System.out.println("Current position: " + buffer.position()); System.out.println("Current limit: " + buffer.limit()); System.out.println("Current content: " + new String(buffer.array())); // 继续向 ByteBuffer 写入数据 buffer.put((byte) 'W') .put((byte) 'o') .put((byte) 'r') .put((byte) 'l') .put((byte) 'd'); // 输出当前 ByteBuffer 的内容 System.out.println("Current position: " + buffer.position()); System.out.println("Current limit: " + buffer.limit()); System.out.println("Current content: " + new String(buffer.array())); // 读取 ByteBuffer 数据 buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); System.out.println("Read data: " + new String(data)); } } ``` 输出结果如下: ``` Current position: 5 Current limit: 10 Current content: Hello Compact the buffer Current position: 5 Current limit: 10 Current content: Hello Current position: 10 Current limit: 10 Current content: World Read data: HelloWorld ``` 可以看到,我们首先创建了一个容量为 10 的 ByteBuffer,并向其写入了 "Hello"。然后,我们调用 `compact()` 方法,将未读取数据ByteBuffer 的起始位置移动,以便继续向其写入数据。接着,我们向 ByteBuffer 写入了 "World",并读取了其数据。最终输出的结果为 "HelloWorld"。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值