JAVA现有一个整型数组{10,20,30,40,50,60,70,80,90,100},使用随机文件流将其存入文件number.txt中,然后将数据读取出来并输出。
时间: 2024-10-20 16:08:19 浏览: 23
04747 Java语言程序设计(一) 2014年4月
在Java中,你可以使用`java.io`包下的`FileWriter`、`BufferedWriter`和`RandomAccessFile`来实现这个功能。以下是步骤:
1. **将整型数组写入文件**:
```java
import java.io.*;
import java.util.Arrays;
public class ArrayToFile {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
String fileName = "number.txt";
try (FileWriter writer = new FileWriter(fileName);
BufferedWriter bufferWriter = new BufferedWriter(writer)) {
// 将数组转换为字符串,逗号分隔
for (int number : numbers) {
bufferWriter.write(number + ",");
}
// 删除最后一个逗号
bufferWriter.write("\n");
bufferWriter.flush();
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}
```
2. **从文件中读取数据并输出**:
```java
public class ReadFile {
public static void main(String[] args) {
String fileName = "number.txt";
try (RandomAccessFile reader = new RandomAccessFile(fileName, "r")) {
long length = reader.length(); // 获取文件长度
byte[] bytes = new byte[(int) length];
reader.readFully(bytes);
// 使用字符串处理工具解析二进制数据
String readString = new String(bytes, StandardCharsets.UTF_8);
String[] numbersStr = readString.split(",");
for (String numberStr : numbersStr) {
System.out.println(Integer.parseInt(numberStr));
}
} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
}
}
}
```
运行这两个程序,首先会把数组存储到文件中,然后读取文件内容并打印。
阅读全文