使用NIO与BIO复制文件性能对比

本文通过案例展示了Java中使用传统IO与NIO方式进行大文件复制的不同效率,并提供了优化建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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毫秒
		 */
	}
	
	
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值