为什么缓冲流时间更长

来源:3-16 自由编程

慕前端2298684

2022-02-16 17:22:49

相关代码:

问题描述:

为什么缓冲流时间更长

相关截图:

https://img.mukewang.com/climg/620cc19209d978c700000000.jpg

package com.imooc.io;

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

public class BD1 {

	public static void main(String[] args) {
		try {
			FileOutputStream fos1 = new FileOutputStream("one.txt");
			FileOutputStream fos2 = new FileOutputStream("two.txt");
			BufferedOutputStream bos = new BufferedOutputStream(fos2);
			int n = 0;
			System.out.println("one.txt不使用缓冲流来写");
			long st1 = System.currentTimeMillis();
			while (n < 1000000) {
				fos1.write('a');
				n = n + 1;
			}
			long ed1 = System.currentTimeMillis();
			System.out.println("时间为" + (ed1 - st1));
			System.out.println("two.txt使用缓冲流来写");
			long st2 = System.currentTimeMillis();
			int i = 0;
			while (i< 1000000) {
				bos.write('a');
				bos.flush();
				i = i + 1;
			}
			long ed2 = System.currentTimeMillis();
			System.out.println("时间为" + (ed2 - st2));
			fos1.close();
			fos2.close();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

搜索

复制

写回答

1回答

好帮手慕阿园

2022-02-16

同学你好,同学将缓冲流中调用flush()方法在写循环外,调用flush()方法也是需要时间的

祝学习愉快~

0

0 学习 · 16556 问题

查看课程