java 高效文件复制_java文件复制的高效方法

在Java编程中,复制文件的方法有很多,而且经常要用到。大伙一般都是用缓冲输入输出流来实现的(绝大多数人都是如此),实际上还存在另一种方法,用文件通道(FileChannel)来实现文件复制竟然比用老方法快了近三分之一。下面我就来介绍一下如何用文件通道来实现文件复制,以及在效率上的对比

1.用文件通道的方式来进行文件复制

/**

* fileChannel方式

*/

public static void fileChannelCopy(File s, File t) {

FileInputStream fi = null;

FileOutputStream fo = null;

FileChannel in = null;

FileChannel out = null;

try {

fi = new FileInputStream(s);

fo = new FileOutputStream(t);

in = fi.getChannel();//得到对应的文件通道

out = fo.getChannel();//得到对应的文件通道

in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

fi.close();

in.close();

fo.close();

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

2.用缓冲文件流得方法

/**

* 文件流方式

* @throws IOException

*/

public static void  copy(File s,File t) throws IOException{

InputStream in=null;

OutputStream out=null;

try{

in= new BufferedInputStream(new FileInputStream(s));

out=new BufferedOutputStream(new FileOutputStream(t));

byte[] b=new byte[1024];

int flag=0;

while((flag=in.read(b))!=-1){

out.write(b, 0, flag);

}

}catch(Exception e){

}finally{

in.close();

out.close();

}

}

3.测试代码

public static void main(String[] args) throws IOException {

File s=new File("d:/tool/adt-bundle-windows-x86-20131030.zip");

File t=new File("e:/t.zip");

long start,end;

start = System.currentTimeMillis();

fileChannelCopy(s,t);

end = System.currentTimeMillis();

System.out.println("channel..."+(end-start));

start =System.currentTimeMillis();

copy(s,t);

end =System.currentTimeMillis();

System.out.println("copy..."+ (end-start));

}

4.测试结果

channel...365

copy...909

5.结论

由此可见,FileChannel复制文件的速度比BufferedInputStream/BufferedOutputStream复制文件的速度快 了近三分之一。在复制大文件的时候更加体现出FileChannel的速度优势。而且FileChannel是多并发线程安全的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值