原文連接 做者:Jakob Jenkov html
Java NIO的通道相似流,但又有些不一樣:java
正如上面所說,從通道讀取數據到緩衝區,從緩衝區寫入數據到通道。以下圖所示:服務器
這些是Java NIO中最重要的通道的實現:網絡
FileChannel 從文件中讀寫數據。dom
DatagramChannel 能經過UDP讀寫網絡中的數據。異步
SocketChannel 能經過TCP讀寫網絡中的數據。code
ServerSocketChannel能夠監聽新進來的TCP鏈接,像Web服務器那樣。對每個新進來的鏈接都會建立一個SocketChannel。orm
下面是一個使用FileChannel讀取數據到Buffer中的示例:htm
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();
注意 buf.flip() 的調用,首先讀取數據到Buffer,而後反轉Buffer,接着再從Buffer中讀取數據。下一節會深刻講解Buffer的更多細節。blog
(全文完)