码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-04-01 21:01:13      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:buffer   提升   不同的   时间   利用   row   write   ges   stream   

   利用不同的读写方式实现复制时,不同的方法对大文件有较大的影响。

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

  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 字节)

 

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

标签:buffer   提升   不同的   时间   利用   row   write   ges   stream   

原文地址:http://www.cnblogs.com/wyfstudy/p/6657506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!