Java NIO的Channel类似流,但是由有所不同:
1. 既可以从通道中读取数据,又可以写入数据到通道。
2. 通道可以异步的读写。
3. 通道中的数据总是要先读取到一个Buffer,或者总是从一个Buffer中写入。
1. Channel的类型
1. FileChannel 从文件中读写数据。
2. DatagramChannel 能通过UDP读写网络中的数据。
3. SocketChannel 能通过TCP读写网络中的数据。
4. ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。
2. 基本Channel示例
下面是一个使用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,然后反转Buffer,接着再从Buffer中读取数据。