老师,想请问这样写可以吗?但是我运行的时间跟图中的不一样哎,这是为什么?

来源:3-16 自由编程

Heijyu

2020-06-21 00:47:57

package com.imooc.io;

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

public class BufferedExercise3_16 {

	public static void main(String[] args) {
		File file1;
		File file2;
		FileOutputStream fos1;
		FileOutputStream fos2;
		BufferedOutputStream bos2;
		try {
			file1 = new File("one.txt");
			file2 = new File("two.txt");
			if (!file1.exists()) {
				file1.createNewFile();
			}
			if (!file2.exists()) {
				file2.createNewFile();
			}
			fos1 = new FileOutputStream(file1);
			long startTimeOne = System.currentTimeMillis();
			for (int i = 0; i < 100000; i++) {
				fos1.write('a');
			}
			long endTimeOne = System.currentTimeMillis();
			long totalTimeOne = endTimeOne - startTimeOne;
			System.out.println(file1.getName() + "不使用缓冲区来写");
			System.out.println("用时为:" + totalTimeOne);

			System.out.println("=====================================");

			fos2 = new FileOutputStream(file2);
			bos2 = new BufferedOutputStream(fos2);
			long startTimeTwo = System.currentTimeMillis();
			for (int i = 0; i < 100000; i++) {
				bos2.write('a');
			}
			bos2.flush();
			long endTimeTwo = System.currentTimeMillis();
			long totalTimeTwo = endTimeTwo - startTimeTwo;
			System.out.println(file2.getName() + "使用缓冲区来写");
			System.out.println("用时为:" + totalTimeTwo);
			System.out.println("节省时间:" + (totalTimeOne - totalTimeTwo));
			fos1.close();
			fos2.close();
			bos2.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

http://img.mukewang.com/climg/5eee3db209ee9bab08720376.jpg

写回答

1回答

好帮手慕阿园

2020-06-21

同学你好,是可以的 , 课题完成的不错 , 很棒 ; 运行结果是不固定的 , 运行结果跟电脑的配置、CPU、内存等因素都有影响的
祝学习愉快

0
heijyu
h 好的,看来我电脑配置太低了?
h020-06-21
共1条回复

0 学习 · 16556 问题

查看课程