javaNIOChannel - juedaiyuer/researchNote GitHub Wiki

#NIO---Channel#

##通道##

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

##channel的实现##

  • FileChannel 从文件中读写数据
  • DatagramChannel 通过UDP读写网络中的数据
  • SocketChannel 能通过TCP读写网络中的数据
  • ServerSocketChannel 可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel

##示例##

package nio;

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

public class channel {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		RandomAccessFile aFile = new RandomAccessFile("/home/juedaiyuer/mycode/test/food_list.txt", "rw");
		FileChannel inChannel = aFile.getChannel();
		
		//分配一个新的字节缓冲区allocate
		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.println((char) buf.get());
			}
		
			buf.clear();
			bytesRead = inChannel.read(buf);
		}
		
			aFile.close();
			 
	}

}


// 另一个测试
// 注意在调用channel的write方法之前必须调用buffer的flip方法,否则无法正确写入内容
public class Test {
	public static void main(String[] args) throws IOException  {
		File file = new File("data.txt");
		FileOutputStream outputStream = new FileOutputStream(file);
		FileChannel channel = outputStream.getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		String string = "java nio";
		buffer.put(string.getBytes());
		buffer.flip();     //此处必须要调用buffer的flip方法
		channel.write(buffer);
		channel.close();
		outputStream.close();
	}  
}

##source##