- Channel 實(shí)現(xiàn)
- 基本 Channel 示例
Java NIO Channels 類似于一些有差異的流:
- 您可以同時(shí)讀取和寫入
Channels,而流通常是單向的(讀或?qū)懀?/li> - Channels 可以被異步讀取和寫入。
- Channels 始終從一個(gè) Buffer 中讀取或?qū)懭搿?/li>
如上所述,您將通道中的數(shù)據(jù)讀入緩沖區(qū),并將數(shù)據(jù)從緩沖區(qū)寫入通道。這是一個(gè)插圖:

Java NIO: Channels and Buffers
Java NIO: Channels read data into Buffers, and Buffers write data into Channels
Channel Implementations
以下是Java NIO中最重要的Channel實(shí)現(xiàn):
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel 從文件中讀取數(shù)據(jù)
DatagramChannel 能夠通過UDP網(wǎng)絡(luò)讀取和寫入數(shù)據(jù)
SocketChannel 能夠通過TCP網(wǎng)絡(luò)去讀和寫入數(shù)據(jù)
ServerSocketChannel 允許你監(jiān)聽即將到來的TCP connections,像web服務(wù)那樣,對(duì)于每一個(gè)即將到來的connection,都會(huì)有一個(gè)SocketChannel被創(chuàng)建。
Basic Channel Example
這是一個(gè)基本的例子,它使用一個(gè) FileChannel來讀取一些數(shù)據(jù)到Buffer:
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() 的調(diào)用。第一步讀取到一個(gè)Buffer中,接著flip()它,再接著從中讀出。我將會(huì)在下一節(jié)介紹關(guān)于更多關(guān)于Buffer的細(xì)節(jié)。
Forward:Java NIO 概述(一)
Next: Java NIO Buffer(三)