欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NIO

程序员文章站 2022-04-23 23:42:57
...

 http://tutorials.jenkov.com/java-nio/socketchannel.html

 

package com.gc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

import junit.framework.TestCase;

public class Test extends TestCase{
	/**
	 * 通道
	 * 缓冲区
	 * 异步IO
	 * 直接缓冲区
	 */
	Charset utf8 = Charset.forName("UTF-8");
	
	CharsetEncoder encoder = utf8.newEncoder();
	CharsetDecoder decoder = utf8.newDecoder();
	
	
	//clear() 方法重设缓冲区,使它可以接受读入的数据。
	//Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.
	public  void testReadWithCharset() throws Exception {
		String fileName = "test.txt";
		FileInputStream fin = new FileInputStream(fileName);
		FileChannel fc = fin.getChannel();
		
		ByteBuffer buffer = ByteBuffer.allocate(100);
		fc.read(buffer);
		
		//从缓冲区读之前必须调用flip()-->设置limit与position的位置
		buffer.flip();
		
		//使用Charset进行解码,正确显示中文
		CharBuffer charBuf = decoder.decode(buffer);
		
		while(charBuf.remaining()>0) {
			System.out.print(charBuf.get());
		}
		
		
		fin.close();
		
	}
	
	//flip() 方法重新调整position和limit在缓冲区数组中的位置,以便将读入的数据完整写入通道。
	//The limit is set to the current position and then the position is set to zero
	public void testWriteWithCharset()throws Exception {
		FileOutputStream fout = new FileOutputStream("write.txt");
		FileChannel fc = fout.getChannel();
		
		CharBuffer buffer = CharBuffer.allocate(1024);
		
		char[] message = {'该','睡','觉','了'};
		
		
		for(int i=0;i<message.length;i++) {
			buffer.put(message[i]);
		}
		
		buffer.flip();//编码之前先调用flip()

		//写数据,必须使用 CharsetEncoder将它转换回字节
		ByteBuffer byteBuf = encoder.encode(buffer);
		
		fc.write(byteBuf);
		
		fout.close();
		
	}
	
	
	//clear() 和 flip() 方法用于让缓冲区在读和写之间切换。 
	public void testCopy()throws Exception {
		
		FileInputStream fin = new FileInputStream("cp-source.txt");
		FileChannel fic = fin.getChannel();
		
		FileOutputStream fout = new FileOutputStream("cp-result.txt");
		FileChannel foc = fout.getChannel();
		
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		while(true) {
			//read
			buffer.clear();
			int r = fic.read(buffer);
			
			if(r==-1)
				break;
			
			//write
			buffer.flip();
			foc.write(buffer);
		}
		
		fin.close();
		fout.close();
	}
	
}