编写一个Java程序,把几个int型整数写入到一个名为“tom.dat”的文件中,然后按相反顺序读出这些数据
时间: 2024-12-29 14:33:42 浏览: 12
在Java中,我们可以使用`java.io`包下的`FileWriter`, `FileReader`, 和 `BufferedReader` 类来实现这个需求。首先,我们需要创建一个文件并写入整数,接着关闭文件,然后再打开并读取内容。
这里是一个简单的示例:
```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// 写入数据
int[] numbers = {10, 20, 30, 40, 50};
String fileName = "tom.dat";
writeToFile(numbers, fileName);
// 读取数据
int[] readNumbers = readFromFile(fileName);
printReverseOrder(readNumbers);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeToFile(int[] numbers, String fileName) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
for (int num : numbers) {
writer.write(num + "\n");
}
writer.close(); // 关闭流
System.out.println("Data written to file successfully.");
}
private static int[] readFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
StringBuilder dataBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
dataBuilder.append(line).append("\n"); // 保留换行符
}
reader.close();
// 将字符串分割成数组
String[] strNumbers = dataBuilder.toString().split("\n");
int[] readNumbers = new int[strNumbers.length];
for (int i = 0; i < strNumbers.length; i++) {
readNumbers[i] = Integer.parseInt(strNumbers[strNumbers.length - 1 - i]); // 反转顺序
}
return readNumbers;
}
private static void printReverseOrder(int[] numbers) {
System.out.println("Reversed numbers:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
```
在这个例子中,我们先将数组转换为字符串并逐行写入文件,然后读取整个文件的内容作为一个字符串,再按照每行分割成数组,并通过索引反转其顺序。
阅读全文