5.文件拷贝

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutionException;
public class TestDemo {
	private static final int BLOCK_SIZE = 20*1024*1024; 
	
	public static void singleThreadRWFile1(File file, File newFile) throws IOException {
		FileInputStream is = new FileInputStream(file);
		FileOutputStream os = new FileOutputStream(newFile);
		
		byte[] buffer = new byte[4096];
		while (is.read(buffer) != -1){ 
			os.write(buffer);
		}
		
		is.close();
		os.close();
	}
	
	public static void singleThreadRWFile2(File file, File newFile) throws IOException{
		FileChannel
			in = new FileInputStream(file).getChannel(),
			out = new FileOutputStream(newFile).getChannel();
			
		ByteBuffer bytebuffer = ByteBuffer.allocate(4096);
		
		while (in.read(bytebuffer) != -1){
			bytebuffer.flip();
			out.write(bytebuffer);
			bytebuffer.clear();
		}
		
		in.close();
		out.close();
	}
	
	public static void singleThreadRWFile3(File file, File newFile) throws IOException{
		FileChannel
		in = new FileInputStream(file).getChannel(),
		out = new FileOutputStream(newFile).getChannel();
		
		in.transferTo(0, in.size(), out);
//		out.transferFrom(in, 0, in.size());
		
		in.close();
		out.close();
	}
	
	public static void clear(File newFile) throws IOException{
		if (newFile.exists()){
			newFile.delete();
			newFile.createNewFile();
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
		// TODO Auto-generated method stub
		File file = new File("E:/copy1.mp4");
		File newFile = new File("E:/copy2.mp4");
		if (!newFile.exists()){
			newFile.createNewFile();
		}
		
		long begin, end;
		begin = System.currentTimeMillis();
		singleThreadRWFile1(file, newFile);
		end = System.currentTimeMillis();
		System.out.println("singleThreadRWFile1() spend time:" + (end-begin) + "s");
		clear(newFile);
		
		begin = System.currentTimeMillis();
		singleThreadRWFile2(file, newFile);
		end = System.currentTimeMillis();
		System.out.println("singleThreadRWFile2() spend time:" + (end-begin) + "s");
		clear(newFile);
		
		begin = System.currentTimeMillis();
		singleThreadRWFile3(file, newFile);
		end = System.currentTimeMillis();
		System.out.println("singleThreadRWFile3() spend time:" + (end-begin) + "s");
		
		System.out.println("main over");
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值