编写一个Java程序将100,101,102,103,104,105以数组的形式升序写入dest.txt文件中,然后以降序读出显示在控制台上,用try catch finally 处理异常
时间: 2024-02-24 10:58:35 浏览: 72
好的,以下是Java程序的实现:
```java
import java.io.*;
public class FileIO {
public static void main(String[] args) {
int[] nums = {100, 101, 102, 103, 104, 105};
String fileName = "dest.txt";
// 写入数组到文件中
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
for (int i = 0; i < nums.length; i++) {
writer.write(nums[i] + "\n");
}
writer.close();
} catch (IOException e) {
System.out.println("写入文件时出错:" + e.getMessage());
}
// 从文件中读取数组并降序输出到控制台上
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int[] arr = new int[nums.length];
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
arr[i++] = Integer.parseInt(line);
}
reader.close();
// 冒泡排序,将数组降序排列
for (int j = 0; j < arr.length - 1; j++) {
for (int k = 0; k < arr.length - 1 - j; k++) {
if (arr[k] < arr[k + 1]) {
int temp = arr[k];
arr[k] = arr[k + 1];
arr[k + 1] = temp;
}
}
}
// 输出降序排列后的数组
for (int j = 0; j < arr.length; j++) {
System.out.println(arr[j]);
}
} catch (IOException e) {
System.out.println("读取文件时出错:" + e.getMessage());
} finally {
// 删除生成的文件
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
}
}
}
```
在这个程序中,我们使用了 `BufferedWriter` 和 `FileWriter` 类来将数组写入文件中,使用了 `BufferedReader` 和 `FileReader` 类来从文件中读取数组,并使用冒泡排序将数组降序排列后再输出到控制台上。在异常处理中,我们使用了 `try-catch-finally` 语句块来确保程序在出现异常时能够正确处理并关闭文件流,并在最后删除生成的文件。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)