您的位置:首页 > 其它

四种复制方法效率比较

2016-12-05 18:11 337 查看
    我们学过了IO流,复制文件是必不可少的,那我们采用哪种方式复制呢?哪种方式的效率更高呢?我们一起来比较一下吧,这样以后就可以根据需求采用合适的方法操作文件了。

【四种复制】

/*
* 四种复制方法,比较速度
*/
public class Copy {
public static void main(String[] args) throws IOException {
File src=new File("f:\\博客书1.rar");//源路径
File dest=new File("f:\\ab\\博客书1.rar");//目标路径
copy_1(src,dest);//用字节一个一个复制
copy_2(src,dest);//用字节数组复制
copy_3(src,dest);//调用缓冲流一个字节一个字节进行复制
copy_4(src,dest);//调用缓冲字节数组进行复制
}
//用字节一个一个复制
public static void copy_1(File src,File dest) throws IOException{
long s=System.currentTimeMillis();
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(dest);
int len=0;
while((len=fis.read())!=-1){
fos.write(len);
}
fos.close();
fis.close();
long e=System.currentTimeMillis();
System.out.println("单个字节复制"+(e-s));
}
//用字节数组复制
public static void copy_2(File src,File dest) throws IOException{
long s=System.currentTimeMillis();
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(dest);
int len=0;
byte [] b=new byte[1024];
while((len=fis.read(b))!=-1){
fos.write(b,0,len);
}
fos.close();
fis.close();
long e=System.currentTimeMillis();
System.out.println("字节数组"+(e-s));
}
//调用缓冲一个字节一个字节进行复制
public static void copy_3(File src,File dest) throws IOException{
long s=System.currentTimeMillis();
FileInputStream fis=new FileInputStream(src);
BufferedInputStream bis=new BufferedInputStream(fis);
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
int len;
while((len=bis.read())!=-1){
bos.write(len);
}
bos.close();
bis.close();
fis.close();
long e=System.currentTimeMillis();
System.out.println("缓冲流单个字节复制"+(e-s));
}
//调用缓冲字节数组进行复制
public static void copy_4(File src,File dest) throws IOException{
long s=System.currentTimeMillis();
FileInputStream fis=new FileInputStream(src);
BufferedInputStream bis=new BufferedInputStream(fis);
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
int len;
byte [] b=new byte[1024];
while((len=bis.read(b))!=-1){
bos.write(b,0,len);
}
bos.close();
bis.close();
fis.close();
long e=System.currentTimeMillis();
System.out.println("缓冲字节数组复制"+(e-s));

}
}


【结果如下】

单位为毫秒



【总结】

    这个结果我们就能一目了然了,如果复制的文件比较小,采用哪种方式都是可以的,但是如果文件大了呢?就体现出缓冲流的作用了,以后具体文件具体分析,让我们的程序飞起来……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: