阅读背景:

使用NIO与BIO复制文件性能对比_is_zhoufeng的专栏

来源:互联网 
package mr.mr03;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.junit.Test;

public class CopyFileTest {
	
	@Test
	public void testBioCopyFile() throws Exception{
		long start = System.currentTimeMillis();
		File fromFile = new File("E:/live_sql/livesql/live-sql.2015-04-24.log");
		File toFile = new File("E:/live_sql/copy/live-sql.2015-04-24.log");
		if(!toFile.exists()){
			toFile.createNewFile();
		}
		FileInputStream fis = new FileInputStream(fromFile);
		FileOutputStream fos = new FileOutputStream(toFile);
		byte[] buf = new byte[1024 * 1024 * 100];
		int copyLen = -1 ;
		while((copyLen = fis.read(buf)) != -1){
			fos.write(buf, 0, copyLen); 
		}
		fis.close();
		fos.close();
		long end = System.currentTimeMillis();
		System.out.println("耗时:" + (end - start) + "毫秒");   
		/**
		 * 文件大小为458M
		 * case1 
		 *	 当buf大小设置为 1024(1kb) 耗时:7290毫秒
		 * case2
		 *  当buf大小设置为1024*1024*10(10M) 耗时:659毫秒
		 * case3
		 *  当buf大小设置为1024*1024*100(100M) 耗时:5252毫秒
		 */
	}
	
	@Test
	public void testNioCopyFile() throws Exception{
		long start = System.currentTimeMillis();
		File fromFile = new File("E:/live_sql/livesql/live-sql.2015-04-24.log");
		File toFile = new File("E:/live_sql/copy/live-sql.2015-04-24.log");
		if(!toFile.exists()){
			toFile.createNewFile();
		}
		FileInputStream fis = new FileInputStream(fromFile);
		FileOutputStream fos = new FileOutputStream(toFile);
		
		FileChannel inputChannel = fis.getChannel();
		FileChannel outputChannel = fos.getChannel();
		ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 1024) ;
		int readLen = -1 ;
		int writeLen = -1 ;
		while((readLen = inputChannel.read(buf)) != -1){
			buf.flip();
			writeLen = outputChannel.write(buf) ;
			if(writeLen != readLen){
				System.out.println("writeLen!=readLen," + writeLen + "," + readLen);  
			}
			buf.clear();
		}
		
		inputChannel.close();
		outputChannel.close();
		fis.close();
		fos.close();
		long end = System.currentTimeMillis();
		System.out.println("耗时:" + (end - start) + "毫秒");   
		
		/**
		 * 文件大小为458M
		 * case1 
		 * 	 ByteBuffer使用allocate分配1024字节  耗时:2234毫秒
		 * case2
		 *   ByteBuffer使用allocate分配1024 * 1024 (1M)  耗时:348毫秒
		 * case3
		 * 	 ByteBuffer使用allocateDirect分配1024 字节  耗时:2081毫秒
		 * case4
		 * 	 ByteBuffer使用allocateDirect分配1024 * 1024 (1M)  耗时:255毫秒
		 */
	}
	
	
}

package mr.mr03;

import java.io.File;
import j



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: