FileInputStream 与 BufferedIutputStream

今天我们来看看当读取大文件的时候FileInputStream与BufferedOutputStream的耗时情况,我们以文件1.CHM为目标文件,来读取它。此文件的大小为35.2MB。

我们将D盘下的1.CHM复制到2.CHM

File file = new File("D:\\1.CHM");
File file2 = new File("D:\\2.CHM");

FileInputStream

1、一次性读取全部文件

long startTime = System.currentTimeMillis();   //开始时间
byte[] b = new byte[(int)file.length()];       
is.read(b);    //读操作
os.write(b);   //写操作
long endTime = System.currentTimeMillis();    //结束时间
System.out.println("耗时:" + (endTime - startTime));    //总耗时
运行结果:
第一次耗时:385ms
第二次耗时:324ms
第三次耗时:307ms
平均耗时:338ms

2、一次性读取一定长度的数据

long startTime = System.currentTimeMillis();           //开始时间
FileInputStream is = new FileInputStream(file);        //建立数据通道
FileOutputStream os = new FileOutputStream(file2);
byte[] buf = null;
if(file.length()/1024/1024/1024 > 0){
    //如果文件大于1G,一次读取1M内容
    buf = new byte[1024*1024];
}else{
    //如果文件大于1M,一次读取1kb内容
    buf = new byte[1024];  
}
int length = 0;  //代表实际读取的字节数
while((length = is.read(buf))!=-1){   //读取文件
    os.write(buf, 0, buf.length);    //将1.CHM文件内容写到2.CHM
}
    is.close();    //关闭缓冲区
    os.close();
    long endTime = System.currentTimeMillis();        //结束时间
    System.out.println("\n耗时:" + (endTime - startTime));      //总耗时
运行结果:
第一次耗时:183ms
第二次耗时:180ms
第三次耗时:184ms
平均耗时:182ms

BufferedIutputStream

long startTime = System.currentTimeMillis();
InputStream bis = new BufferedInputStream(new FileInputStream(file)); //将FileInputStream作为参数传入,建立数据通道
OutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
byte[] bs = new byte[1024];
int length = 0;
while((length = bis.read(bs, 0, bs.length)) != -1){
	bos.write(bs, 0, bs.length);
	bos.flush();    //清空缓冲区,迫使缓冲区的数据全部写出
}
bis.close();
bos.close();
long endTime = System.currentTimeMillis();
System.out.println("\n消耗时间:" + (endTime - startTime));
运行结果:
第一次耗时:140ms
第二次耗时:138ms
第三次耗时:144ms
平均耗时:140ms

总结:

在读取大文件的时候BufferedIutputStream优于FileInputStream。

猜你喜欢

转载自blog.csdn.net/qq_37618797/article/details/81041400