本文采用四种方法将同样的数据从一个文件复制到另外一个文件中,并对其进行计时统计,并作了结果对比
四种方法分别为:
1,用基本字节流一次读写一个字节
2,用基本字节流一次读写一个字节数组
3,用高效字节流一次读写一个字节
4, 用高效字节流一次读写一个字节数组
下面来看代码:
package a003; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class TestDemo { public static void main(String[] args) throws IOException{ long start=System.currentTimeMillis(); Method1("h:\\a.txt","h:\\ed.txt"); long end=System.currentTimeMillis(); System.out.println("总耗时:"+(end-start)+"毫秒"); } //用高效字节流一次读写一个字节数组 public static void Method4(String src,String dest)throws IOException{ BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest)); byte[] bys=new byte[1024]; int len=0; while((len=bis.read(bys))!=-1){ bos.write(bys,0,len); } bis.close(); bos.close(); } //用高效字节流一次读写一个字节 public static void Method3(String src,String dest)throws IOException{ BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest)); int len=0; while((len=bis.read())!=-1){ bos.write(len); } bis.close(); bos.close(); } //用基本字节流一次读写一个字节 public static void Method1(String src,String dest)throws IOException{ FileInputStream fis=new FileInputStream(src); FileOutputStream fos=new FileOutputStream(dest); int len=0; while((len=fis.read())!=-1){ fos.write(len); } fis.close(); fos.close(); } //用基本字节流一次读写一个字节数组 public static void Method2(String src,String dest)throws IOException{ FileInputStream fis=new FileInputStream(src); FileOutputStream fos=new FileOutputStream(dest); byte[] bys=new byte[1024]; int len=0; while((len=fis.read(bys))!=-1){ fos.write(bys,0,len); } fis.close(); fos.close(); } }
计算结果统计对比:
method1:总耗时:127毫秒
method2:总耗时:1毫秒
method3:总耗时:32毫秒
method4:总耗时:1毫秒
从上面的输出结果可以看出,在同等情况下,一次传输一个字节数组的方法的传输速度明显高于一次传输一个字节的方法,不管是高效字节流还是普通的字节流中,尽管在method2和method4都为一毫秒,看起来似乎两个传输速度几乎相同。
但是,问题是因为文中测试的数据量太小,如果是数据量足够大的话,高效字节流的优势肯定会体现出来,读者不妨自己找一个大一点的数据试试,比如视频文件。
文中难免有不足之处,还望大家不吝纠正和指导,谢谢
java中利用串流装饰器进行文件读写的速度对比
最新推荐文章于 2022-08-03 19:41:57 发布