老师帮忙检查一下
来源:3-16 自由编程
MAYxDAY
2020-02-10 20:13:20
package com.imooc.file;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferDemo {
public static void main(String[] args) {
try {
FileOutputStream one = new FileOutputStream("one.txt");
FileOutputStream one1 = new FileOutputStream("two.txt");
BufferedOutputStream two = new BufferedOutputStream(one1);
System.out.println("one.txt不使用缓冲流来写");
long startTime1 = System.currentTimeMillis();
for (int i = 1; i <= 10000; i++) {
one.write(1);
}
one.close();
long endTime1 = System.currentTimeMillis();
System.out.println("用时为" + (endTime1 - startTime1));
long x=endTime1 - startTime1;
System.out.println("two.txt使用缓冲流来写");
long startTime2 = System.currentTimeMillis();
for (int i = 1; i <= 10000; i++) {
two.write(1);
}
two.close();
long endTime2 = System.currentTimeMillis();
System.out.println("用时为" + (endTime2 - startTime2));
long y=endTime2 - startTime2;
System.out.println("节省时间:"+(x-y));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1回答
同学你好,代码编写的不错,但是同学忘记编写关闭流one1的方法了。及时关闭流,避免一直占用系统内存,消耗资源等问题。
另外,流关闭的顺序:建议在统一在代码最后关闭流,先打开的后关闭,后打开的先关闭。就比如我们进行开门时,从大门打开,然后打开卧室门,进入房间,出去时,在我们进行关门时,就要先关卧室门,再关大门。
如:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题