zoukankan      html  css  js  c++  java
  • Java NIO Channel

    Java NIO Channel

     

    Jakob Jenkov
    Last update: 2014-06-23

    Java NIO Channels are similar to streams with a few differences:

    • You can both read and write to a Channels. Streams are typically one-way (read or write).
    • Channels can be read and written asynchronously.
    • Channels always read to, or write from, a Buffer.

    NIO可读可写,流只能读或者写

    Channel可以异步的读和写

    Channel读到buffer,从buffer里写到Channel

    As mentioned above, you read data from a channel into a buffer, and write data from a buffer into a channel. Here is an illustration of that:

    Java NIO: Channels and Buffers
    Java NIO: Channels read data into Buffers, and Buffers write data into Channels

    Channel Implementations

    Channel的一些实现类

    Here are the most important Channel implementations in Java NIO:

    • FileChannel
    • DatagramChannel
    • SocketChannel
    • ServerSocketChannel

    The FileChannel reads data from and to files.

    The DatagramChannel can read and write data over the network via UDP.

    The SocketChannel can read and write data over the network via TCP.

    The ServerSocketChannel allows you to listen for incoming TCP connections, like a web server does. For each incoming connection a SocketChannel is created.

    Basic Channel Example

    一个Channel的例子

    Here is a basic example that uses a FileChannel to read some data into a 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();
    注意这个flip()方法,一开始你是读到buffer,然后调用flip(),变成从buffer里读东西出来。

    Notice the buf.flip() call. First you read into a Buffer. Then you flip it. Then you read out of it. I'll get into more detail about that in the next text about Buffer's.

  • 相关阅读:
    hdu1716排列2(stl:next_permutation+优先队列)
    iOS UIWebView 载入https 网站出现NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL,
    C++学习笔记23,类内函数重载
    Java---16---多线程---死锁
    Ubuntu上的Hadoop安装教程
    SAP BAPI一览 史上最全
    python脚本从excel表到处数据,生成指定格式的文件
    hdu 4865 Peter's Hobby
    【VUE】100. vue踩坑集锦
    【VUE】2.搭建vue脚手架@vue/cli,新建第一个vue项目
  • 原文地址:https://www.cnblogs.com/dzhou/p/9560246.html
Copyright © 2011-2022 走看看