编写一个java程序,将{1,2,3,4,5}的5个数以数组的形式写入到Test.txt文件中,并以相反的顺序读出显示在屏幕上。程序中要有异常处理部分
时间: 2023-02-06 15:24:59 浏览: 101
这是一个使用 Java 写入和读取数组并处理异常的示例程序:
```
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
// 将数组写入到文件
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("Test.txt"));
for (int i = 0; i < array.length; i++) {
writer.write(Integer.toString(array[i]));
writer.newLine();
}
writer.close();
System.out.println("数组已写入到文件");
} catch (IOException e) {
System.out.println("写入文件时出现异常:" + e.getMessage());
}
// 以相反的顺序读取数组并显示在屏幕上
try {
Scanner scanner = new Scanner(new FileReader(new File("Test.txt")));
int[] reversedArray = new int[array.length];
int i = 0;
while (scanner.hasNextInt()) {
reversedArray[i] = scanner.nextInt();
i++;
}
scanner.close();
for (int j = reversedArray.length - 1; j >= 0; j--) {
System.out.println(reversedArray[j]);
}
} catch (FileNotFoundException e) {
System.out.println("读取文件时出现异常:" + e.getMessage());
}
}
}
```
在这个程序中,我们使用了 `BufferedWriter` 和 `FileWriter` 类将数组写入到文件中,使用了 `Scanner` 和 `FileReader` 类从文件中读取数组。我们还在 `try-catch` 语句块中处理了可能出现的异常,包括 `IOException` 和 `FileNotFoundException`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)