初识ByteBuffer入门

2020-04-01  本文已影响0人  xuanAndJava

前言

ByteBuffer是nio/aio编程所必须掌握的一个数据结构,也是掌握tio所必须要学会的基础只是。
设想,如果你不懂Map,List,Set,那么你在编程领域将会一事无成,同样的道理,如果你不懂ByteBuffer,你无法在nio/aio编程领域立足。

初识ByteBuffer

创建ByteByffer

image.png
image.png

往ByteBuffer中写入数据,观察limit 和 poisuruib的变化

使用put方法即可添加数据到byteBuffer中


image.png

从ButeBuffer中读取数据

对于刚刚写好的bytebuffer,我们读取数据的时候,需要先设置一个position和limit,否则读的位置则不对

        //创建一个 capacity 为6 的ByteBuffer
        ByteBuffer allocate = ByteBuffer.allocate(6);
        allocate.put((byte)1);
        System.out.println(allocate);
        //设置limit为1,那么表示buffter的有效数据长度是1
        allocate.limit(1);
        //设置position到0位置,这样都诗句的时候就从这个位置开始读
        allocate.position(0);
        System.out.println(allocate);
        //get获取一个字节,position 的位置也会随着读取而改变
        byte b = allocate.get();
        System.out.println(allocate);
image.png

文章参考:https://www.t-io.org/doc/tio/83?pageNumber=1

上一篇下一篇

猜你喜欢

热点阅读