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的更多细节。

相关文章
相关标签/搜索