zoukankan      html  css  js  c++  java
  • Java NIO Channel(三)

    原文链接:http://tutorials.jenkov.com/java-nio/channels.html

    Java NIO Channel

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

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

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

      放一张老图:

                               

        Channel Implementations

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

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

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

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

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

      ServerSocketChannel,允许你监听采用TCP的连接

        Basic Channel Example

      这里有一个FileChannel向Buffer里读入数据的例子

      

     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()方法。之后你就可以读取出来。

      

  • 相关阅读:
    最终一致性解决实例
    分布式事务一致性方案
    分布式事务
    OSX
    JAVA
    Eclipse
    Activiti
    CentOS
    用Visual Studio 2015 编写 MASM 汇编程序(二)从头开发一个Win32汇编程序
    Oracle
  • 原文地址:https://www.cnblogs.com/AI-Cobe/p/10020377.html
Copyright © 2011-2022 走看看