最后更新时间:2014-06-23
Java NIO Channels与流类似,也有一些不同之处:
- 对于一个Channels,你可以同时读和写。而流是典型的一个方向的(读或者写)
- Channels可以异步的读写。
- Channels总是读到一个Buffer,或者从一个Buffer写。
正如上面所提的,你读数据从一个channel读到bufffer,以及从一个buffer写数据到一个channel。这里有一个关于那个的图解:
Channel实现
在Java NIO中有几个最重要的Channel实现:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
这个FileChannel是从文件中读写数据
这个DatagramChannel可以通过UDP在网络中读写数据
这个SocketChannel可以通过TCP在网络中读写数据
这个ServerSocketChannel允许你监听进来的TCP连接,就像一个WEB服务器一样。对于每一个进来的连接,一个SocketChannel就会被创建。
基础的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的内容在下一章节中我将会有更详细的介绍。
翻译地址:http://tutorials.jenkov.com/java-nio/channels.html