- Channel 实现
- 基本 Channel 示例
Java NIO Channels 类似于一些有差异的流:
- 您可以同时读取和写入
Channels
,而流通常是单向的(读或写)。 - Channels 可以被异步读取和写入。
- Channels 始终从一个 Buffer 中读取或写入。
如上所述,您将通道中的数据读入缓冲区,并将数据从缓冲区写入通道。这是一个插图:
Java NIO: Channels and BuffersJava NIO: Channels read data into Buffers, and Buffers write data into Channels
Channel Implementations
以下是Java NIO中最重要的Channel实现:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel
从文件中读取数据
DatagramChannel
能够通过UDP网络读取和写入数据
SocketChannel
能够通过TCP网络去读和写入数据
ServerSocketChannel
允许你监听即将到来的TCP connections,像web服务那样,对于每一个即将到来的connection,都会有一个SocketChannel
被创建。
Basic Channel Example
这是一个基本的例子,它使用一个 FileChannel来读取一些数据到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()
的调用。第一步读取到一个Buffer
中,接着flip()
它,再接着从中读出。我将会在下一节介绍关于更多关于Buffer
的细节。