Java NIO系列教程(二) Channel

Java NIO的通道相似流,但又有些不一樣:java

  • 既能夠從通道中讀取數據,又能夠寫數據到通道。但流的讀寫一般是單向的。服務器

  • 通道能夠異步地讀寫。網絡

  • 通道中的數據老是要先讀到一個Buffer,或者老是要從一個Buffer中寫入。dom

正如上面所說,從通道讀取數據到緩衝區,從緩衝區寫入數據到通道。以下圖所示:異步

Channel的實現

這些是Java NIO中最重要的通道的實現:spa

  • FileChannelip

  • DatagramChannelget

  • SocketChannelio

  • ServerSocketChannelclass

FileChannel 從文件中讀寫數據。

DatagramChannel 能經過UDP讀寫網絡中的數據。

SocketChannel 能經過TCP讀寫網絡中的數據。

ServerSocketChannel能夠監聽新進來的TCP鏈接,像Web服務器那樣。對每個新進來的鏈接都會建立一個SocketChannel。

基本的 Channel 示例

下面是一個使用FileChannel讀取數據到Buffer中的示例:

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class T {
 public static void main(String[] args) throws IOException {
  RandomAccessFile aFile = new RandomAccessFile("test.dat", "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() 的調用,首先讀取數據到Buffer,而後反轉Buffer,接着再從Buffer中讀取數據。下一節會深刻講解Buffer的更多細節。

相關文章
相關標籤/搜索