2.Java NIO系列教程之Channel

Java NIO的通道类似流,但又有些不同:

  • 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
  • 通道可以异步地读写。
  • 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:

2.Java NIO系列教程之Channel_第1张图片

Channel的实现

这些是Java NIO中最重要的通道的实现:

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

FileChannel 从文件中读写数据。

DatagramChannel 能通过UDP读写网络中的数据。

SocketChannel 能通过TCP读写网络中的数据。

ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。

基本的 Channel 示例

下面是一个使用FileChannel读取数据到Buffer中的示例:

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


public class NIODemo1 {
	public static void main(String[] args) {
		try{
			RandomAccessFile aFile = new RandomAccessFile("data/nio-data2.txt", "rw");
			FileChannel inChannel = aFile.getChannel();

			//分配10个字节的空间,limit为10
			ByteBuffer buf = ByteBuffer.allocate(10);
			
			//将read中读取的数据写入到buf
			//返回值为读取的字节数,可以为0,如果读到最后,则返回-1
			int bytesRead = inChannel.read(buf);
			while (bytesRead != -1) {

				System.out.println("Read " + bytesRead);
				//buf.flip() 的调用,首先写入到Buffer,然后反转Buffer,接着再从Buffer中读取数据
				buf.flip();
				//Tells whether there are any elements between the current position and the limit. 
				while(buf.hasRemaining()){
					//Reads the byte at this buffer's current position, and then increments the position. 
					System.out.print((char) buf.get());
				}
				System.out.println("\n");
				buf.clear();//make buffer ready for writing
				//此时继续向buf中写入数据,无需先调用flip,查看flip和clear的源码,即可明白
				bytesRead = inChannel.read(buf);
			}
			aFile.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
}




原文地址:http://ifeve.com/channels/



你可能感兴趣的:(java,nio)