JAVA NIO简明教程三 Channel频道

JAVA NIO简明教程三 Channel频道

nio的channels和之前的流(stream)是相似的但是有些一些不同:

  • channels能同时读写,流只能读或者写
  • channels读写是异步的
  • channels总是读写数据从Buffer

正如上面所说,你可以从channel读数据写入buffer,或者从buffer读数据写入channel。下图是示例说明

overview-channels-buffers

channel 的实现类

下面是channel最常用的实现:

  • FileChannel 读写文件
  • DatagramChannel UDP
  • SocketChannel TCP
  • ServerSocketChannel 监听tcp连接,当有连接SocketChannel被创建处理连接

简单示例

下面是一个简单的示例,使用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(),buf.flip()是用来调整缓存的游标指针的。我们将在后续的章节中介绍更多细节。

发布了121 篇原创文章 · 获赞 56 · 访问量 167万+

猜你喜欢

转载自blog.csdn.net/u013565163/article/details/83539738