Java NIO Channel

來源:互聯網
上載者:User

標籤:with   aix   most   tip   create   important   Koa   table   oca   

Java NIO Channel
  • Channel Implementations
  • Basic Channel Example
 

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 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.

Java NIO Channel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.