Java NIO 的Channels和流(stream)很像,但是有如下区别:
- Channels既能读又能写,Stream只能读或者写
- Channels能异步读写
- Channels只能读到Buffer中,或者从Buffer写入
Channel实例
以下是Java NIO中重要的的Channel实例:
- FileChannel:从/往文件中读/写
- DatagramChannel:通过UDP读写网络数据
- SocketChannel:通过TCP读写网络数据
- ServerSocketChannel:监听接入的TCP连接,就像web服务器那样。对于每个接入进来的TCP连接都创建一个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);
文件nio-data.txt:
1234567890
1234567890
1234567890
1234567890
1234567890
1234567890
输出结果为:
Read 48
1234567890
1234567890
1234567890
1234567890
1234Read 17
567890
1234567890