Java NIO系列教程(二) Channel

 

原文連接 做者:Jakob Jenkov    html

Java NIO的通道相似流,但又有些不一樣:java

  • 既能夠從通道中讀取數據,又能夠寫數據到通道。但流的讀寫一般是單向的。
  • 通道能夠異步地讀寫。
  • 通道中的數據老是要先讀到一個Buffer,或者老是要從一個Buffer中寫入。

正如上面所說,從通道讀取數據到緩衝區,從緩衝區寫入數據到通道。以下圖所示:服務器

Channel的實現

這些是Java NIO中最重要的通道的實現:網絡

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

FileChannel 從文件中讀寫數據。dom

DatagramChannel 能經過UDP讀寫網絡中的數據。異步

SocketChannel 能經過TCP讀寫網絡中的數據。code

ServerSocketChannel能夠監聽新進來的TCP鏈接,像Web服務器那樣。對每個新進來的鏈接都會建立一個SocketChannel。orm

基本的 Channel 示例

下面是一個使用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

(全文完)

相關文章
相關標籤/搜索