java文件复制

使用普通的按字节读取,再写入另一个文件,速度太慢。Java提供的JavaChannel能显著提升速度(暂时不知道原理)


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileCopy {
	public static void main(String[] args) {
		String from="e:/Thunder_dl_V7.9.37.4952_setup.1433748298.exe";
		String to="e:/copy/target.exe";
		File fileFrom=new File(from);
		File fileTo=new File(to);
		long start=System.currentTimeMillis();
		//normalCopy(fileFrom,fileTo);
		fastCopy(fileFrom, fileTo);
		long end=System.currentTimeMillis();
		System.out.println("复制文件所用时间是:"+(end-start)+"ms");
	}
	
	public static void normalCopy(File fileFrom,File fileTo){
		int b;
		FileInputStream from=null;
		FileOutputStream to=null;
		try {
			from=new FileInputStream(fileFrom);
			to=new FileOutputStream(fileTo);
			while((b=from.read())!=-1){
				to.write(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("没有找到文件");
			e.printStackTrace();
			System.exit(-1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("文件复制错误");
			e.printStackTrace();
			System.exit(-1);
		} finally {
			try {
				from.close();
				to.close();
			} catch(IOException e){
				e.printStackTrace();
			}
		}

	}
	
	public static void fastCopy(File fileFrom,File fileTo){
		FileInputStream from=null;
		FileOutputStream to=null;
		FileChannel in=null;
		FileChannel out=null;
		try {
			from=new FileInputStream(fileFrom);
			to=new FileOutputStream(fileTo);
			in=from.getChannel();//获取通道
			out=to.getChannel();//
			in.transferTo(0, in.size(), out);  //java提供的复制方法
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("没有找到文件");
			e.printStackTrace();
			System.exit(-1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("文件复制错误");
			e.printStackTrace();
			System.exit(-1);
		} finally {
			try {			
				from.close();
				in.close();
				to.close();
				out.close();
			} catch(IOException e){
				e.printStackTrace();
			}
		}

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值