nio是 java new io 的簡寫 可以代替原來 io所進行的操作
old io 是面向流stream的
new io 是面向 緩沖區(qū)的
認識nio 必須知道幾個重點 緩沖區(qū)buffer 通道channel
nio 讀取數(shù)據(jù)到緩沖區(qū)的兩種模式
- 直接緩沖區(qū) ( 通過allocatedircate()取得緩沖區(qū))
- 非直接緩沖區(qū)( 通過 allocate()取得緩沖區(qū))
區(qū)別:前者盡力不再內(nèi)存中創(chuàng)建副本,后者才副本中進行實現(xiàn)
- 非直接緩沖區(qū):通過 allocate() 方法分配緩沖區(qū),將緩沖區(qū)建立在 JVM 的內(nèi)存中
- 直接緩沖區(qū):通過 allocateDirect() 方法分配直接緩沖區(qū),將緩沖區(qū)建立在物理內(nèi)存中??梢蕴岣咝?/li>
buffer使用
認識五大關鍵 capacity limit position mark reset
構造數(shù)據(jù)對象原子數(shù)據(jù)類型除了boolean以外都是可以的
bytebuffer,charbuffer,longbuffer''''''''''''''''''''''''''''''''''''''''''

bytebuffer.allocate(1024);就會取得五個屬性
初始化position =0 limit=capacity=1024 mark記錄當前位置 reset恢復position到mark標記位置
0<=mark<=positon<=limit<=capacity
常用方法

···
String str = "abcde";
//取得緩沖區(qū)
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
System.out.println("--------------put---------------");
buffer.put(str.getBytes());
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
System.out.println("--------------filp讀寫---------------");
buffer.flip();
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
System.out.println("--------------get---------------");
byte[] dst=new byte[buffer.limit()];
buffer.get(dst);//取到了五個數(shù)據(jù)
System.out.println(new String(dst, 0, 2));
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
System.out.println("--------------reward---------------");
//重新執(zhí)行讀取,恢復位置
buffer.rewind();
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
System.out.println("--------------mark---------------");
System.out.println(buffer.mark());
System.out.println("--------------clear---------------");
//6. clear() : 清空緩沖區(qū). 但是緩沖區(qū)中的數(shù)據(jù)依然存在,但是處于“被遺忘”狀態(tài)
buffer.clear();
System.out.println((char)buffer.get());
}
···
···
String str = "abcde";
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put(str.getBytes());
buf.flip();
byte[] dst = new byte[buf.limit()];
buf.get(dst, 0, 2);
System.out.println(new String(dst, 0, 2));
System.out.println(buf.position());
// mark() : 標記
buf.mark();
buf.get(dst, 2, 2);
System.out.println(new String(dst, 2, 2));
System.out.println(buf.position());
// reset() : 恢復到 mark 的位置
buf.reset();
System.out.println(buf.position());
// 判斷緩沖區(qū)中是否還有剩余數(shù)據(jù)
if (buf.hasRemaining()) {
// 獲取緩沖區(qū)中可以操作的數(shù)量
System.out.println(buf.remaining());
}
···
channel 通道
分散:從buffer讀取數(shù)據(jù)到多個 buffer文件
聚集:從多個buffer讀取數(shù)據(jù)到channel
獲取channel getchannel()
filechanel 文件datagramchannel udp serversocketchannel tcp
socketchannel
類:
fileinputstream /fileoutputstream randomaccessfile datagram serversocket
socket
jdk 1.7 支持 openchannel() files 下 newbytechannel