NIO ByteBuffer方法學習

2021-08-25 14:42:52 字數 1876 閱讀 3752

/**

* 建立heapbytebuffer例項,大小為1024位元組

*/bytebuffer heapbytebuffer = bytebuffer.allocate(1024);

/** * 建立directbytebuffer例項,大小為1024位元組

* 這裡的bytebuffer是directbytebuffer,不是heapbytebuffer.特點是用的記憶體是堆外記憶體

* 減少了複製的時間.該類的個別bytebuffer的方法無法使用,可以檢視原始碼,如array();

*/bytebuffer directbytebuffer = bytebuffer.allocatedirect(1024);

string msg = "hello world";

/** * 往bytebuffer裡放資料

*/heapbytebuffer.put(msg.getbytes());

/** * 取資料

*/heapbytebuffer.get();

/** * 重置了position、limit、mark的值.一般為了下次往bytebuffer裡放資料做準備

*/heapbytebuffer.clear();

/** * bytebuffer是否還有資料未被讀取. 原始碼就是 通過position < limit 返回乙個布林值

*/heapbytebuffer.hasremaining();

/** * 本質就是設定position、limit、mark的值.一般為了從bytebuffer讀出資料做準備

*/heapbytebuffer.flip();

/** * 將讀過的釋放,沒讀過的複製到陣列起始位置,position為未讀過的長度,等待繼續put.

* position為未讀過的長度.

* limit為容器大小

* mark為-1

*/heapbytebuffer.compact();

/** * 就是返回position這個屬性

*/heapbytebuffer.position();

/** * 就是返回limit這個屬性

*/heapbytebuffer.limit();

/** * 就是返回capacity這個屬性

*/heapbytebuffer.capacity();

/** * 返回bytebuffer裡的byte,往heapbytebuffer放的資料和的讀的資料都來自這個byte

* 注意: directbytebuffer不適用.

* 原始碼裡isreadonly為true或者byte為null的使用該方法會拋異常

*/heapbytebuffer.array();

/** * 做標記,就是將現在position的值(索引)賦給mark

*/heapbytebuffer.mark();

/** * 是否是只可讀的buffer

*/heapbytebuffer.isreadonly();

/** * 是否是directbytebuffer

*/heapbytebuffer.isdirect();

/** * 判斷是否有byte陣列,判斷依據是(hb != null) && !isreadonly

*/heapbytebuffer.hasarray();

/** * 本質就是limit - position

*/heapbytebuffer.remaining();

/** * 將position重置到mark的位置

*/heapbytebuffer.reset();

/** * 將position置0,mark置-1

*/heapbytebuffer.rewind();

nio ByteBuffer碰到的問題

bytebuffer1.allocate服務端接收不到op read事件問題 bytebuffer bytebuffer bytebuffer.allocate length sc.write bytebuffer 通過allocate建立的bytebuffer,需要呼叫下filp 方法,不呼叫,s...

方法的呼叫 this方法 構造方法

1 呼叫者和被呼叫者方法位於同一類中,呼叫形式如下 this 方法名 在大多數情況下,關鍵字this可以忽略 呼叫者位於被呼叫方法所在類的外部 物件名.方法名或者類名.方法名 抽象類只能作為父類,不能例項化。只能被繼承 抽象方法是一種只有方法宣告而沒有方法體定義的特殊方法,最後有乙個分號 而沒有方法...

例項方法 靜態方法 類方法

首先新建乙個日期date類,屬性為年,月,日,tomorrow 是例項方法,這個最常見,比較簡單,例項方法的第乙個引數是例項物件self 當我們傳入的年月日是2018 6 4這樣的形式,我們就需要先進行字串處理,在這裡使用了元組的拆包 這是最基本的方式,但是這樣寫會有乙個問題,每次傳參都需要進行字串...