前言
ByteBuffer是nio/aio編程所必須掌握的一個(gè)數(shù)據(jù)結(jié)構(gòu),也是掌握tio所必須要學(xué)會(huì)的基礎(chǔ)只是。
設(shè)想,如果你不懂Map,List,Set,那么你在編程領(lǐng)域?qū)?huì)一事無成,同樣的道理,如果你不懂ByteBuffer,你無法在nio/aio編程領(lǐng)域立足。
初識(shí)ByteBuffer
- byte[] bytes : 用來存儲(chǔ)數(shù)據(jù)
- int capacity:用來表示bytes的容量,那么可以想象capacity就等于bytes.siez(),此值在初始化bytes后,是不可變的。
- int limit:用來表示bytes時(shí)機(jī)裝了多少數(shù)據(jù),可以容易現(xiàn)象到limit<=capacity,此值是可變動(dòng)的。
-
int position:用那表示在哪個(gè)位置開始往bytes寫數(shù)據(jù)或讀數(shù)據(jù),此值是可靈活變動(dòng)的。
image.png
創(chuàng)建ByteByffer

image.png

image.png
往ByteBuffer中寫入數(shù)據(jù),觀察limit 和 poisuruib的變化
使用put方法即可添加數(shù)據(jù)到byteBuffer中

image.png
從ButeBuffer中讀取數(shù)據(jù)
對(duì)于剛剛寫好的bytebuffer,我們讀取數(shù)據(jù)的時(shí)候,需要先設(shè)置一個(gè)position和limit,否則讀的位置則不對(duì)
//創(chuàng)建一個(gè) capacity 為6 的ByteBuffer
ByteBuffer allocate = ByteBuffer.allocate(6);
allocate.put((byte)1);
System.out.println(allocate);
//設(shè)置limit為1,那么表示buffter的有效數(shù)據(jù)長度是1
allocate.limit(1);
//設(shè)置position到0位置,這樣都詩句的時(shí)候就從這個(gè)位置開始讀
allocate.position(0);
System.out.println(allocate);
//get獲取一個(gè)字節(jié),position 的位置也會(huì)隨著讀取而改變
byte b = allocate.get();
System.out.println(allocate);

image.png
