1.分别使用FileWriter和BufferedWriter往文件中写入10万个随机数(Math.random()),比较用时的多少。(System.currentTimeMillis();//获取当前时间)
时间: 2024-11-29 08:34:42 浏览: 0
比较Filewriter 与bufferwriter
5星 · 资源好评率100%
为了比较`FileWriter`和`BufferedWriter`在写入10万个随机数到文件时的性能差异,我们可以创建一个简单的示例来测量它们各自完成任务所需的时间。以下是大致步骤:
1. 首先,导入必要的库:
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
```
2. 定义一个函数用于生成并写入随机数:
```java
public void writeRandomNumbers(int numIterations, BufferedWriter writer) throws IOException {
Random random = new Random();
long startTime = System.currentTimeMillis();
for (int i = 0; i < numIterations; i++) {
double randomNumber = random.nextDouble(); // 生成随机数
writer.write(String.valueOf(randomNumber)); // 写入文件
writer.newLine(); // 每行结束换行
}
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("Elapsed time using " + writer.getClass().getName() + ": " + elapsedTime + "ms");
}
```
3. 使用`FileWriter`和`BufferedWriter`分别写入10万个随机数,并记录时间:
```java
public static void main(String[] args) {
File outputFile = new File("random_numbers.txt");
try {
FileWriter fileWriter = new FileWriter(outputFile);
writeRandomNumbers(100000, fileWriter);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
writeRandomNumbers(100000, bufferedWriter);
bufferedWriter.close(); // 关闭BufferedWriter,释放资源
} catch (IOException e) {
e.printStackTrace();
}
// 添加时间对比部分
long fileWriteTime = System.currentTimeMillis() - startWriteTime; // 获取两者的总耗时
System.out.println("Total elapsed time writing to file: " + fileWriteTime + "ms");
阅读全文