Java NIO 02 === Channel

Source: Internet
Author: User

Java NIO 02 === Channel

The Java NIO channel is similar to a stream, but it is somewhat different:

  • Data can be read from the channel and written to the channel. However, stream read/write is usually unidirectional.
  • The channel can be read and written asynchronously.
  • The data in the channel always needs to read a Buffer first, or always needs to be written from a Buffer.

    As mentioned above, data is read from the channel to the buffer zone, and data is written from the buffer zone to the channel. As shown in:

     

    Channel implementation

    These are the most important channel implementations in Java NIO:

    • FileChannel
    • DatagramChannel
    • SocketChannel
    • ServerSocketChannel

      FileChannel reads and writes data from a file.

      Mongoramchannel can read and write data in the network through UDP.

      SocketChannel can read and write data in the network through TCP.

      The ServerSocketChannel can listen to new TCP connections, just like the Web server. A SocketChannel is created for each new connection.

      Basic Channel example

      The following is an example of using FileChannel to read data to the 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();

       

      Help

      Pay attention to the call of buf. flip (). First, read the data to the Buffer, then reverse the Buffer, and then read the data from the Buffer. The next section will explain more details about the Buffer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.