(1) 分别使用FileWriter 和 BufferedWriter 往文件exp5_1.txt和文件exp5_2.txt中写入1万个随机整数(数与数之间用空格隔开),并在控制台上显示程序运行的时间。(exp5_1.java) (提示:用时采用方法System.currentTimeMillis()求时间差。)
时间: 2024-03-03 20:53:21 浏览: 52
以下是exp5_1.java的代码实现:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class exp5_1 {
public static void main(String[] args) {
int n = 10000;
Random random = new Random();
// 使用FileWriter写入
long start1 = System.currentTimeMillis();
try {
FileWriter fileWriter = new FileWriter("exp5_1.txt");
for (int i = 0; i < n; i++) {
int num = random.nextInt(1000);
fileWriter.write(num + " ");
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
long end1 = System.currentTimeMillis();
// 使用BufferedWriter写入
long start2 = System.currentTimeMillis();
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("exp5_2.txt"));
for (int i = 0; i < n; i++) {
int num = random.nextInt(1000);
bufferedWriter.write(num + " ");
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
long end2 = System.currentTimeMillis();
// 输出程序运行时间
System.out.println("FileWriter写入时间:" + (end1 - start1) + "ms");
System.out.println("BufferedWriter写入时间:" + (end2 - start2) + "ms");
}
}
```
程序先生成10000个随机整数,然后使用FileWriter和BufferedWriter分别往文件exp5_1.txt和文件exp5_2.txt中写入这些整数,最后输出程序运行时间。
阅读全文