學習NIO 更新中

2021-09-25 14:25:19 字數 2141 閱讀 4972

nio是基於通道進行資料的傳輸,緩衝區進行資料的訪問;

緩衝區(buffer)本質是陣列,儲存不同資料型別的資料 (除了boolean型別);

所有的緩衝區管理方式幾乎一致,通過allocate()分配指定大小的緩衝區

bytebuffer buf = bytebuffer.

allocate

(1024);

//分配1024位元組的bytebuffer的緩衝區

緩衝區的四個核心屬性:

下邊列印一下buf的各個值

system.out.

println

(buf.

position()

);

system.out.

println

(buf.

limit()

);system.out.

println

(buf.

capacity()

);

快取區的訪問

string str =

"abcde"

; buf.

put(str.

getbytes()

);system.out.

println

("*****===put*****====");

system.out.

println

(buf.

position()

);system.out.

println

(buf.

limit()

);system.out.

println

(buf.

capacity()

);

這時候再看一下各個值

position隨著讀入,逐漸向右移動到5的位置,而limit和capacity不變。

用flip()函式切換到讀取資料模式

buf.

flip()

;//切換到讀取資料模式

system.out.

println

("*****===flip*****====");

system.out.

println

(buf.

position()

);system.out.

println

(buf.

limit()

);system.out.

println

(buf.

capacity()

);

發現position回到原位,limit變成資料的後邊。

讀資料

byte

dst =

newbyte

[buf.

limit()

];buf.

get(dst)

; system.out.

println

(new

string

(dst,

0,dst.length));

system.out.

println

("*****===get*****====");

system.out.

println

(buf.

position()

);system.out.

println

(buf.

limit()

);system.out.

println

(buf.

capacity()

);

position確實隨著讀出而移動。

NIO學習一 NIO簡介

最近在學習nio,根據學習總結了一下,如果有不對的地方,請大佬指出。nio,就是new io,從jdk 1.4開始引入的新的api,它跟io的作用相同。它與傳統的io相比,有如下特性 1 nio是面向緩衝區的,io是面向流的。2 io是阻塞的操作,如果乙個io的read或者write沒有得到資料的時...

學習NIO小結

nio 同步非阻塞 在jdk1.4時推出,和傳統的io 同步阻塞 比較有著新的思想,在網上學習和整理知識點時知道學習nio可分為3個部分 1.channel 通道,資料的讀取和寫入都可以通過它來完成。2.selector 選擇器,用於選擇註冊在通道中的已發生的事件。3.bytebuffer 乙個新的...

NIO學習總結

使用傳統的i o讀取檔案內容 param filepath 檔案路徑 throws ioexception public static void ioread string filepath throws ioexception 使用nio讀取檔案內容 param filepath 檔案路徑 thr...