Java NIO中的Channel和Stream很像,但是又有一些不同點:
- 在Channel中可讀也可寫(雙工)的。一般來說Stream是可讀或者可寫(單工)的。
- Channel的讀和寫可以是異步的。
- Channel面向的是Buffer。
正如上面提到的,通過Channel可以讀又可以寫,下圖說明了這一點:
Channel的實現
下面列出了一些重要的實現類:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel是用讀寫文件的。
DatagramChannel是用來通過UDP協議讀寫數據的。
SocketChannel是用來通過TCP協議讀寫數據的。
ServerSocketChannel可以監聽TCP連接,類似一個web服務一樣。對於每個接入的連接都會創建一個SocketChannel(因此,以聊天室的應用場景爲例,使用selector管理多個channel就會很高效)。
Channel基礎示例
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中。然後調用flip函數,才能把buffer中的數據取出來。後面會詳細介紹這一部分內容。