Java NIO Channel(三)

原文连接:http://tutorials.jenkov.com/java-nio/channels.htmlhtml

Java NIO Channel

  • Channel 的实现
  • 简单的Channel例子

  Java NIO和标准的IO流,有一些不一样的地方:java

  1. 对于channel,你能够写或者读。而stream的话,只能写或只能读。
  2. channel的读和写是异步的。
  3. channel的读和写老是和buffer相关联。

  放一张老图:网络

                           

    Channel Implementations

  如下是Java NIO中重要的channel实现类dom

  1. FileChannel
  2. DatagramChannel
  3. SocketChannel
  4. ServerSocketChannel

  FileChannel,读取或写入数据到file(文件)异步

  DatagramChannel,经过网络读取或写入数据,采用UDP协议spa

  SocketChannel,经过网络读取或写入数据,采用TCP协议code

  ServerSocketChannel,容许你监听采用TCP的链接htm

    Basic Channel Example

  这里有一个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

相关文章
相关标签/搜索