原文连接:http://tutorials.jenkov.com/java-nio/channels.htmlhtml
Java NIO和标准的IO流,有一些不一样的地方:java
放一张老图:网络
如下是Java NIO中重要的channel实现类dom
FileChannel,读取或写入数据到file(文件)异步
DatagramChannel,经过网络读取或写入数据,采用UDP协议spa
SocketChannel,经过网络读取或写入数据,采用TCP协议code
ServerSocketChannel,容许你监听采用TCP的链接htm
这里有一个FileChannel向Buffer里读入数据的例子blog
1 RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); 2 FileChannel inChannel = aFile.getChannel(); 3 4 ByteBuffer buf = ByteBuffer.allocate(48); 5 6 int bytesRead = inChannel.read(buf); 7 while (bytesRead != -1) { 8 9 System.out.println("Read " + bytesRead); 10 buf.flip(); 11 12 while(buf.hasRemaining()){ 13 System.out.print((char) buf.get()); 14 } 15 16 buf.clear(); 17 bytesRead = inChannel.read(buf); 18 } 19 aFile.close();
注意,调用的flip()方法,当你将数据读取到buffer中后,你须要调用flip()方法。以后你就能够读取出来。ip