IO---Java 不同读写方式的IO性能

来源:互联网 发布:软件服务外包方案 编辑:程序博客网 时间:2024/05/01 04:58
   利用不同的读写方式实现复制时,不同的方法对大文件有较大的影响。

   下面就三种方式测试一下。

  Ps:System.currentMillis();用于记录那一刻的时间。

1.利用单字节的方式直接复制(速度慢)

实现方法如下

public static void dzj(File infile,File outfile) throws IOException{    FileInputStream in =new FileInputStream(infile);    FileOutputStream out=new FileOutputStream(outfile);    if(!infile.exists())        throw new IllegalArgumentException("此文件不存在");    if(!infile.isFile())        throw new IllegalArgumentException("此文件不是目录");    long a=System.currentTimeMillis();    int i;    while((i=in.read())!=-1){        out.write(i);        out.flush();    }    long b=System.currentTimeMillis();    System.out.println("单字节直接复制用时"+(b-a));    in.close();    out.close();}

2.利用缓冲区Bufferef提高性能(速度有较为明显的提高)

public static void hc(File infile,File outfile)throws IOException{    BufferedInputStream in=new BufferedInputStream(new FileInputStream(infile));    BufferedOutputStream  out=new BufferedOutputStream(new FileOutputStream(outfile));        if(!infile.isFile())        throw new IllegalArgumentException("这不是文件");    if(!infile.exists())        throw new IllegalArgumentException("文件不存在");    long a=System.currentTimeMillis();    int i;    while((i=in.read())!=-1){        out.write(i);        out.flush();        }    long b=System.currentTimeMillis();    System.out.println("读写用缓冲区的用时为:"+(b-a));    in.close();    out.close();}

 

3.利用字节数组批量读写字节(速度提升非常明显,开辟了内存)

public static void bytes(File infile,File outfile)throws IOException{    FileInputStream in =new FileInputStream(infile);    FileOutputStream out =new FileOutputStream(outfile);    if(!infile.exists())        throw new IllegalArgumentException("文件不存在");    if(!infile.isFile())        throw new IllegalArgumentException("不是文件");    long a=System.currentTimeMillis();    int bytes;    byte []buf=new byte[20*1024];    while((bytes=in.read(buf,0,buf.length))!=-1){        out.write(buf, 0, bytes);        out.flush();    }    long b=System.currentTimeMillis();    System.out.println("字节数组方法用时为:"+(b-a));    in.close();    out.close();}

 

以上代码运行结果如下:

测试文件为  10.1 MB (10,616,738 字节)

 

0 0
原创粉丝点击