四种复制方法效率比较
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)); } }
【结果如下】
单位为毫秒【总结】
这个结果我们就能一目了然了,如果复制的文件比较小,采用哪种方式都是可以的,但是如果文件大了呢?就体现出缓冲流的作用了,以后具体文件具体分析,让我们的程序飞起来……相关文章推荐
- HashMap的四种遍历方法,及效率比较
- 使用字节流复制文件的四种方式以及效率比较
- 比较C#中几种常见的复制字节数组方法的效率
- 比较C#中几种常见的复制字节数组方法的效率[转]
- java数组复制的四种方法效率对比
- 四种字节流复制文件的效率比较
- JAVA生成和解析XML的四种方法比较
- 线程同步的几种方法效率比较
- [转]Java中四种操作XML方法的比较
- 几种字符串反转方法效率比较
- 三种字符串连接方法的效率比较
- 【测试】两种数据库,四种分页算法的效率比较
- 【测试】两种数据库,四种分页算法的效率比较
- 几种字符串反转方法效率比较
- ORACLE批量更新四种方法比较
- Applet与Servlet通讯的四种方法及其比较
- C#中数组复制的四种方法
- 图像透明拷贝 - 不同方法的效率比较
- [C#]几种字符串反转方法效率比较
- 几种字符串反转方法效率比较