关于文件拷贝效率问题(面试总结)

昨天面试被问到拷贝一个文件如何提高效率,当时没想就说利用多线程,将文件分成多块,分别复制。面试官质问读文件可以分别读,那写文件如何写?因为每个线程运行的顺序是随机的。可能我对随机读写文件掌握的不太好,就没继续说下去了。

今天仔细整理了一面试的问题,面试官想得到的答案应该是采用缓存来复制文件。不过用多线程随机读写(RandomAccessFile)也是可以的。自己总结一下java拷贝文件的几种方式:


1.不采用缓存,读一次写一次

public static void copy1(String input,String output){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(new File(input));
			fos = new FileOutputStream(new File(output));
			int in = 0;
			while((in=fis.read())!=-1){
				fos.write(in);
//				System.out.println(in);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
测试代码:
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		String input = "d:/linkMap.txt";
		String output = "d:/output.txt";
		copy(input,output);
		long endTime = System.currentTimeMillis();
		System.out.println((endTime-startTime)+"ms");
	}
文件大小为16.7MB。运行的时间为:27036ms

2、采用缓存字节数组

public static void copy(String input, String output) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			byte[] buffer = new byte[1024];
			fis = new FileInputStream(new File(input));
			fos = new FileOutputStream(new File(output));
			int len = 0;
			while ((len = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
同样大小的文件运行时间为360ms。

可见采用缓存来读写文件的效率是惊人的。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值