为什么我不使用缓冲流反而用时更少?

为什么我不使用缓冲流反而用时更少?

package com.imooc.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedTime {

	public static void main(String[] args) {
		try {
			FileOutputStream fos2 = new FileOutputStream("two.txt");
			BufferedOutputStream bos2 = new BufferedOutputStream(fos2);
			FileOutputStream fos1 = new FileOutputStream("one.txt");
			//不使用缓冲流来写入100000个a
			int n1 = 0;
			long startTime1 = System.currentTimeMillis();
			while(n1<100000) {
				fos1.write('a');
				n1++;
			}
			long endTime1 = System.currentTimeMillis();
			long time1 = endTime1-startTime1;
			System.out.println("one.txt不使用缓冲流来写\n用时为:"+time1);
			//使用缓冲流来写入100000个a
			int n2 = 0;
			long startTime2 = System.currentTimeMillis();
			while(n2<100000) {
				bos2.write('a');
				n2++;
				bos2.flush();
			}
			long endTime2 = System.currentTimeMillis();
			long time2 = endTime2-startTime2;
			System.out.println("two.txt使用缓冲流来写\n用时为:"+time2);
			
			System.out.println("节省时间:"+(time1-time2)+"ms");
			fos1.close();
			bos2.close();
			fos2.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}
//one.txt不使用缓冲流来写
//用时为:242
//two.txt使用缓冲流来写
//用时为:254
//节省时间:-12ms


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学你好,首先每写一行数据就调用flush方法,会降低写入效率。其次在close方法中已经隐式调用了flush方法,所以,将while循环中的bos2.flush()去掉。http://img1.sycdn.imooc.com//climg/5cac227d0001bf8706250592.jpg如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~



问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师