老师帮忙看下这道题写的有没有问题!谢谢!
来源:3-16 自由编程
VapeMage
2020-02-09 01:36:27
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));
}
}1回答
同学你好,代码没有问题,但有一个小建议,建议同学计算节省的时间。修改后代码如下:

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题