Skip to content

Latest commit

 

History

History
46 lines (31 loc) · 1.57 KB

File metadata and controls

46 lines (31 loc) · 1.57 KB

#03. Java NIO通道

Java NIO的通道(Channels)类似与标准IO中的流(Stream),它们之间的区别在于:

  • 你可以从管道中读取或写入数据(双向),但是流只能是读取或写入(单向)。
  • 通道可以进行异步(Asynchonously)操作。
  • 通道(Channel)总是从缓冲区(Buffers)中读取或写入数据。

如上面所提到的,数据总是从管道中读取到缓冲区,后从缓冲区中写入到通道。如下图所示:

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

以下是Java NIO中Chanel的最重要的实现类:

  • FileChannel:从文件中读取或写入数据
  • DatagramChannel:从UPD中读取或写入数据
  • SocketChannel:从TCP中读取或写入数据
  • ServerSocketChannel:用于监听TCP连接,每接收一个连接就创建一个SocketChannel

##Channel例子(Basic Channel Example)

以下的代码示例演示了从FileChannel读取数据到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();

注意buf.flip的调用。当你写入数据到Buffer后,需要调用这个方法,然后才能从Buffer中读取数据。