java 非缓冲与缓冲数据写入比较

//非缓冲计时
package
com.swust; import java.io.*; /* *功能:创建一个程序,写10000个随机双精度的数到一个文件中,同时测试运用缓冲和非缓冲技术 * 进行这种操作所需要的时间 *分析: * 写双精度数到磁盘中的代码和之前文章类似。在写开始操作之前,先获取当前时间 * 再将它同操作结束后的时间作比较,以此判断各个操作的时间 *实现: * 仍使用两个类: */ public class flowTest { public static void main(String[] args) { try{ long start=System.currentTimeMillis(); FileOutputStream fs_out =new FileOutputStream("sample.ini"); DataOutputStream out=new DataOutputStream(fs_out); for (int i=0;i<10000;i++){ out.writeDouble(Math.random()); } out.close(); long stop=System.currentTimeMillis(); System.out.println("程序运行了:"+(stop-start)); }catch(Exception e){ System.out.println(e.toString()); } } }

程序运行了:31


使用缓冲的对比:

//缓冲计时
package com.swust;
import java.io.*;
/*
 *功能:创建一个程序,写10000个随机双精度的数到一个文件中,同时测试运用缓冲和非缓冲技术
 *        进行这种操作所需要的时间
 *分析:
 *   此时使用缓冲的方法,只需将文件输出流和数据输出流相连之前把它“包装”到一个缓冲输出流中去
 *实现:
 *   仍使用两个类:
 *   DataOutputStream的数据通过BufferedOutputStream“包装”,然后使用桥梁FileOutputStream进行
 *   “流”操作
 */
public class flowTest {
 
    public static void main(String[] args) {
    
          
          try{
              long start=System.currentTimeMillis();
              FileOutputStream fs_out =new FileOutputStream("sample.ini");
              ///////////////////////////////////
              
              BufferedOutputStream bfs_out =new  BufferedOutputStream(fs_out);
              DataOutputStream out=new DataOutputStream(bfs_out);
              
              ///////////////////////////////////
              for (int i=0;i<10000;i++){
                  out.writeDouble(Math.random());
              }
              out.close();
              long stop=System.currentTimeMillis();
              System.out.println("程序运行了:"+(stop-start));
          }catch(Exception e){
              System.out.println(e.toString());
          }
          
    }
    

}

程序运行了:15

总结:缓冲流是一个增加了内部缓存的流。当一个简单的写请求产生后,数据并不是马上写到所连接的输出流和文件中,而是写入高速缓存。

当缓冲写满或关闭流之后,再一次性从缓存中写入输出流或者文件中。这样可以减少实际写请求的次数,以此提高数据写入文件中的效率。

类似地,从一个带有缓存的输入流读取数据,也可先把缓存读满,随后的读请求直接从缓存中而不是从文件中读取,这种方式大大提高了读取数据的效率。

原文地址:https://www.cnblogs.com/shuqingstudy/p/4728667.html