1.Java NIO 簡介java
2.Java NIO 與IO 的主要區別數組
3.緩衝區(Buffer)和通道(Channel)網絡
4.文件通道(FileChannel)app
5.NIO 的非阻塞式網絡通訊dom
選擇器(Selector)
SocketChannel、ServerSocketChannel、DatagramChannel工具
面向流性能
面向緩衝區大數據
Java NIO(New IO)是從Java 1.4版本開始引入的一個新的IO API,能夠替代標準的Java IO API。NIO與原來的IO有一樣的做用和目的,可是使用的方式徹底不一樣,NIO支持面向緩衝區的、基於通道的IO操做。NIO將以更加高效的方式進行文件的讀寫操做。編碼
Java NIO 與IO 的主要區別spa
import java.nio.ByteBuffer;
import org.junit.Test;
/*
*/
public class TestBuffer {
@Test public void test3(){ //分配直接緩衝區 ByteBuffer buf = ByteBuffer.allocateDirect(1024); System.out.println(buf.isDirect()); } @Test public void test2(){ 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()); //判斷緩衝區中是否還有剩餘數據 if(buf.hasRemaining()){ //獲取緩衝區中能夠操做的數量 System.out.println(buf.remaining()); } } @Test public void test1(){ String str = "abcde"; //1. 分配一個指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println("-----------------allocate()----------------"); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); //2. 利用 put() 存入數據到緩衝區中 buf.put(str.getBytes()); System.out.println("-----------------put()----------------"); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); //3. 切換讀取數據模式 buf.flip(); System.out.println("-----------------flip()----------------"); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); //4. 利用 get() 讀取緩衝區中的數據 byte[] dst = new byte[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()); //5. rewind() : 可重複讀 buf.rewind(); System.out.println("-----------------rewind()----------------"); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); //6. clear() : 清空緩衝區. 可是緩衝區中的數據依然存在,可是處於「被遺忘」狀態 buf.clear(); System.out.println("-----------------clear()----------------"); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); System.out.println((char)buf.get()); }
}
1-通道(Channel)與緩衝區(Buffer)
通道和緩衝區
Java NIO系統的核心在於:通道(Channel)和緩衝區(Buffer)。通道表示打開到IO 設備(例如:文件、套接字)的鏈接。若須要使用NIO 系統,須要獲取用於鏈接IO 設備的通道以及用於容納數據的緩衝區。而後操做緩衝區,對數據進行處理。
緩衝區(Buffer)
緩衝區(Buffer):一個用於特定基本數據類
型的容器。由java.nio 包定義的,全部緩衝區
都是Buffer 抽象類的子類。
Java NIO 中的Buffer 主要用於與NIO 通道進行
交互,數據是從通道讀入緩衝區,從緩衝區寫
入通道中的。
緩衝區(Buffer)
Buffer 就像一個數組,能夠保存多個相同類型的數據。根
據數據類型不一樣(boolean 除外) ,有如下Buffer 經常使用子類:
ByteBuffer
CharBuffer
ShortBuffer
IntBuffer
LongBuffer
FloatBuffer
DoubleBuffer
上述Buffer 類他們都採用類似的方法進行管理數據,只是各自
管理的數據類型不一樣而已。都是經過以下方法獲取一個Buffer
對象:
緩衝區的基本屬性
Buffer 中的重要概念:
容量(capacity) :表示Buffer 最大數據容量,緩衝區容量不能爲負,而且創
建後不能更改。
限制(limit):第一個不該該讀取或寫入的數據的索引,即位於limit 後的數據
不可讀寫。緩衝區的限制不能爲負,而且不能大於其容量。
位置(position):下一個要讀取或寫入的數據的索引。緩衝區的位置不能爲
負,而且不能大於其限制
標記(mark)與重置(reset):標記是一個索引,經過Buffer 中的mark() 方法
指定Buffer 中一個特定的position,以後能夠經過調用reset() 方法恢復到這
個position.
緩衝區的基本屬性
Buffer 的經常使用方法
緩衝區的數據操做
Buffer 全部子類提供了兩個用於數據操做的方法:get()
與put() 方法
獲取Buffer 中的數據
get() :讀取單個字節
get(byte[] dst):批量讀取多個字節到dst 中
get(int index):讀取指定索引位置的字節(不會移動position)
放入數據到Buffer 中
put(byte b):將給定單個字節寫入緩衝區的當前位置
put(byte[] src):將src 中的字節寫入緩衝區的當前位置
put(int index, byte b):將指定字節寫入緩衝區的索引位置(不會移動position)
直接與非直接緩衝區
字節緩衝區要麼是直接的,要麼是非直接的。若是爲直接字節緩衝區,則Java 虛擬機會盡最大努力直接在
此緩衝區上執行本機I/O 操做。也就是說,在每次調用基礎操做系統的一個本機I/O 操做以前(或以後),
虛擬機都會盡可能避免將緩衝區的內容複製到中間緩衝區中(或從中間緩衝區中複製內容)。
直接字節緩衝區能夠經過調用此類的allocateDirect() 工廠方法來建立。此方法返回的緩衝區進行分配和取消
分配所需成本一般高於非直接緩衝區。直接緩衝區的內容能夠駐留在常規的垃圾回收堆以外,所以,它們對
應用程序的內存需求量形成的影響可能並不明顯。因此,建議將直接緩衝區主要分配給那些易受基礎系統的
本機I/O 操做影響的大型、持久的緩衝區。通常狀況下,最好僅在直接緩衝區能在程序性能方面帶來明顯好
處時分配它們。
直接字節緩衝區還能夠經過FileChannel 的map() 方法將文件區域直接映射到內存中來建立。該方法返回
MappedByteBuffer 。Java 平臺的實現有助於經過JNI 從本機代碼建立直接字節緩衝區。若是以上這些緩衝區
中的某個緩衝區實例指的是不可訪問的內存區域,則試圖訪問該區域不會更改該緩衝區的內容,而且將會在
訪問期間或稍後的某個時間致使拋出不肯定的異常。
字節緩衝區是直接緩衝區仍是非直接緩衝區可經過調用其isDirect() 方法來肯定。提供此方法是爲了可以在
性能關鍵型代碼中執行顯式緩衝區管理。
非直接緩衝區
直接緩衝區
通道(Channel)
通道(Channel):由java.nio.channels 包定義
的。Channel 表示IO 源與目標打開的鏈接。
Channel 相似於傳統的「流」。只不過Channel
自己不能直接訪問數據,Channel 只能與
Buffer 進行交互。
通道(Channel)
通道(Channel)
Java 爲Channel 接口提供的最主要實現類以下:
•FileChannel:用於讀取、寫入、映射和操做文件的通道。
•DatagramChannel:經過UDP 讀寫網絡中的數據通道。
•SocketChannel:經過TCP 讀寫網絡中的數據。
•ServerSocketChannel:能夠監聽新進來的TCP 鏈接,對每個新進來
的鏈接都會建立一個SocketChannel。
獲取通道
獲取通道的一種方式是對支持通道的對象調用
getChannel() 方法。支持通道的類以下:
FileInputStream
FileOutputStream
RandomAccessFile
DatagramSocket
Socket
ServerSocket
獲取通道的其餘方式是使用Files 類的靜態方法newByteChannel() 獲
取字節通道。或者經過通道的靜態方法open() 打開並返回指定通道。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.junit.Test; /* * 1、通道(Channel):用於源節點與目標節點的鏈接。在 Java NIO 中負責緩衝區中數據的傳輸。Channel 自己不存儲數據,所以須要配合緩衝區進行傳輸。 * * 2、通道的主要實現類 * java.nio.channels.Channel 接口: * |--FileChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * 3、獲取通道 * 1. Java 針對支持通道的類提供了 getChannel() 方法 * 本地 IO: * FileInputStream/FileOutputStream * RandomAccessFile * * 網絡IO: * Socket * ServerSocket * DatagramSocket * * 2. 在 JDK 1.7 中的 NIO.2 針對各個通道提供了靜態方法 open() * 3. 在 JDK 1.7 中的 NIO.2 的 Files 工具類的 newByteChannel() * * 4、通道之間的數據傳輸 * transferFrom() * transferTo() * * 5、分散(Scatter)與彙集(Gather) * 分散讀取(Scattering Reads):將通道中的數據分散到多個緩衝區中 * 彙集寫入(Gathering Writes):將多個緩衝區中的數據彙集到通道中 * * 6、字符集:Charset * 編碼:字符串 -> 字節數組 * 解碼:字節數組 -> 字符串 * */ public class TestChannel { //字符集 @Test public void test6() throws IOException{ Charset cs1 = Charset.forName("GBK"); //獲取編碼器 CharsetEncoder ce = cs1.newEncoder(); //獲取解碼器 CharsetDecoder cd = cs1.newDecoder(); CharBuffer cBuf = CharBuffer.allocate(1024); cBuf.put("威武!"); cBuf.flip(); //編碼 ByteBuffer bBuf = ce.encode(cBuf); for (int i = 0; i < 12; i++) { System.out.println(bBuf.get()); } //解碼 bBuf.flip(); CharBuffer cBuf2 = cd.decode(bBuf); System.out.println(cBuf2.toString()); System.out.println("------------------------------------------------------"); Charset cs2 = Charset.forName("GBK"); bBuf.flip(); CharBuffer cBuf3 = cs2.decode(bBuf); System.out.println(cBuf3.toString()); } @Test public void test5(){ Map<String, Charset> map = Charset.availableCharsets(); Set<Entry<String, Charset>> set = map.entrySet(); for (Entry<String, Charset> entry : set) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } //分散和彙集 @Test public void test4() throws IOException{ RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw"); //1. 獲取通道 FileChannel channel1 = raf1.getChannel(); //2. 分配指定大小的緩衝區 ByteBuffer buf1 = ByteBuffer.allocate(100); ByteBuffer buf2 = ByteBuffer.allocate(1024); //3. 分散讀取 ByteBuffer[] bufs = {buf1, buf2}; channel1.read(bufs); for (ByteBuffer byteBuffer : bufs) { byteBuffer.flip(); } System.out.println(new String(bufs[0].array(), 0, bufs[0].limit())); System.out.println("-----------------"); System.out.println(new String(bufs[1].array(), 0, bufs[1].limit())); //4. 彙集寫入 RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw"); FileChannel channel2 = raf2.getChannel(); channel2.write(bufs); } //通道之間的數據傳輸(直接緩衝區) @Test public void test3() throws IOException{ FileChannel inChannel = FileChannel.open(Paths.get("d:/1.mkv"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("d:/2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); // inChannel.transferTo(0, inChannel.size(), outChannel); outChannel.transferFrom(inChannel, 0, inChannel.size()); inChannel.close(); outChannel.close(); } //使用直接緩衝區完成文件的複製(內存映射文件) @Test public void test2() throws IOException{//2127-1902-1777 long start = System.currentTimeMillis(); FileChannel inChannel = FileChannel.open(Paths.get("d:/1.mkv"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("d:/2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); //內存映射文件 MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()); //直接對緩衝區進行數據的讀寫操做 byte[] dst = new byte[inMappedBuf.limit()]; inMappedBuf.get(dst); outMappedBuf.put(dst); inChannel.close(); outChannel.close(); long end = System.currentTimeMillis(); System.out.println("耗費時間爲:" + (end - start)); } //利用通道完成文件的複製(非直接緩衝區) @Test public void test1(){//10874-10953 long start = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; //①獲取通道 FileChannel inChannel = null; FileChannel outChannel = null; try { fis = new FileInputStream("d:/1.mkv"); fos = new FileOutputStream("d:/2.mkv"); inChannel = fis.getChannel(); outChannel = fos.getChannel(); //②分配指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //③將通道中的數據存入緩衝區中 while(inChannel.read(buf) != -1){ buf.flip(); //切換讀取數據的模式 //④將緩衝區中的數據寫入通道中 outChannel.write(buf); buf.clear(); //清空緩衝區 } } catch (IOException e) { e.printStackTrace(); } finally { if(outChannel != null){ try { outChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if(inChannel != null){ try { inChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } long end = System.currentTimeMillis(); System.out.println("耗費時間爲:" + (end - start)); } }