二、Channel

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

  • 既可以从通道中读取数据,又可以写数据到通道中。但流的读取通常的单向的。

  • 通道可以异步地读写

  • 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

Channel的实现

    下面是NIO中重要的通道实现。

         FileChannel                          从文件中读取数据

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

  • SocketChannel                     通过TCP读取网络中的数据

  • ServerSocketChannel           监听TCP连接,对新进来的连接都会创建一个SocketChannel。

    基本的Channel示例

    

package nio;

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

public class channel {
	void cha() throws IOException{
		
		RandomAccessFile aFile = new RandomAccessFile("d:/date/nio.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();
	}
	
	public static void main(String[] args) {
		channel s= new channel();
		try {
			s.cha();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

    注意buf.flip()的调用,首先读数据到Buffer,然后反转Buffer,接着从Buffer中读取数据。

你可能感兴趣的:(二、Channel)