麻烦老师看下我的代码
来源:3-16 自由编程
home_11
2021-05-09 12:16:41
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file1 = new File("one.txt");
File file2 = new File("two.txt");
try {
if (!file1.exists()) {
file1.createNewFile();
}
if (!file2.exists()) {
file2.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
final int N = 100000;
byte[] chs = new byte[N];
for (int i = 0; i < N; ++i) {
chs[i] = (byte) (Math.random() * 128);
}
try {
FileOutputStream fos = new FileOutputStream(file1);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
long before;
before = System.currentTimeMillis();
for(byte ch: chs) {
fos.write(ch);
}
fos.close();
before = System.currentTimeMillis() - before;
System.out.println("one.txt不使用缓冲流来写\n用时为:" + before);
long next;
next = System.currentTimeMillis();
for(byte ch: chs) {
bos.write(ch);
}
bos.flush();
bos.close();
next = System.currentTimeMillis() - next;
System.out.println("two.txt使用缓冲流来写\n用时为:" + next);
System.out.println("节省时间:" + (before - next) + "ms");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

1回答
好帮手慕小尤
2021-05-09
同学的代码完成的不错,继续加油。
祝学习愉快!
相似问题