帮我写个具有下面功能的java代码1 创建文件number.txt, 里面存放多个整数。 2 读取该文件里面的数据,并统计平均值,最大值,最小值。 3. 将统计的信息及数据排序后 写入result.txt中。
时间: 2024-03-01 18:54:42 浏览: 24
好的,以下是满足你要求的 Java 代码:
```java
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
// 1. 创建文件 number.txt,里面存放多个整数
FileWriter writer = new FileWriter("number.txt");
writer.write("1 2 3 4 5 6 7 8 9 10");
writer.close();
// 2. 读取该文件里面的数据,并统计平均值,最大值,最小值。
Scanner scanner = new Scanner(new File("number.txt"));
List<Integer> nums = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
nums.add(scanner.nextInt());
}
scanner.close();
double avgNum = nums.stream().mapToInt(Integer::intValue).average().getAsDouble();
int maxNum = Collections.max(nums);
int minNum = Collections.min(nums);
// 3. 将统计的信息及数据排序后写入 result.txt 中。
FileWriter writer2 = new FileWriter("result.txt");
writer2.write(String.format("平均值:%f\n", avgNum));
writer2.write(String.format("最大值:%d\n", maxNum));
writer2.write(String.format("最小值:%d\n", minNum));
writer2.write("排序后的数据:\n");
Collections.sort(nums);
for (int num : nums) {
writer2.write(num + "\n");
}
writer2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
此代码会在当前目录下创建 `number.txt` 文件,存储了数字 1 到 10。然后读取该文件中的数据,并统计平均值、最大值、最小值。最后将统计的信息及数据排序后写入 `result.txt` 文件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)