老师帮忙看下这道题写的有没有问题!谢谢!
package file;
import java.io.*;
/**
* 编写一个Java程序,将100000个字符分别写入文件one.txt和文件two.txt,one用不加缓冲的文件输出流来写,two用缓冲文件输出流来写,比较用时的多少。
* 1、用FileOutputStream写one;
* 2、用BufferedOutputStream写two;
* 3、写100000个字符,可以使用for循环一次写入一个。
*/
public class BufferedDemo2 {
public static void main(String[] args) {
//创建两个文件
File file1 = new File("one.txt");
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("two.txt");
if (!file2.exists()) {
try {
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//将100000个字符写入one.txt文件,不用缓冲流来写
long startTime = System.currentTimeMillis();
try {
FileOutputStream fos = new FileOutputStream("one.txt", true);
char c = 'a';
for (int i = 0; i < 100000; i++) {
fos.write(c);
c++;
}
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("不用缓冲流写入时间:"+(endTime - startTime));
//将100000个字符写入two.txt文件,用缓冲流来写
long startTime1 = System.currentTimeMillis();
try {
FileOutputStream fos1 = new FileOutputStream("two.txt",true);
BufferedOutputStream bos1 = new BufferedOutputStream(fos1);
char c = 'a';
for (int i = 0; i < 100000; i++){
bos1.write(c);
c++;
}
bos1.flush();
fos1.close();
bos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
long endTime1 = System.currentTimeMillis();
System.out.println("用缓冲流写入时间:"+(endTime1 - startTime1));
}
}11
收起
正在回答
1回答
同学你好,代码没有问题,但有一个小建议,建议同学计算节省的时间。修改后代码如下:

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星