创建文件number.txt,里面存放多个整数 2 读取该文件里面的数据,并统计亚均值,最大值,最小值。 3.将统计的信息及数据排序后 写入result.txt中。 用Java实现
时间: 2024-02-19 14:58:32 浏览: 115
好的,这里是一个Java的实现:
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FileIOExample {
public static void main(String[] args) {
String inputFileName = "number.txt";
String outputFileName = "result.txt";
List<Integer> numbers = new ArrayList<>();
// 1. 读取文件内容并计算平均值、最大值和最小值
try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) {
String line;
int sum = 0;
int count = 0;
int maxNum = Integer.MIN_VALUE;
int minNum = Integer.MAX_VALUE;
while ((line = reader.readLine()) != null) {
int num = Integer.parseInt(line.trim());
numbers.add(num);
sum += num;
count++;
maxNum = Math.max(maxNum, num);
minNum = Math.min(minNum, num);
}
double avg = (double) sum / count;
// 2. 将信息及排序后的结果写入result.txt中
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {
writer.write("平均值:" + avg + "\n");
writer.write("最大值:" + maxNum + "\n");
writer.write("最小值:" + minNum + "\n");
Collections.sort(numbers);
for (int num : numbers) {
writer.write(num + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
代码中的注释已经解释了每一步的实现过程。如果您有其他问题,请随时提出。
阅读全文