编写java程序,给定两个数组int[]numbers={1,2,3,4,5};String[]cities={"北京","上海","广州"};编写一个序列化和反序列化程序,把上述数组内容写入文件array.dat,然后,把array.dat文件的数据读出保存到数组int[]newNumbers和String[]newStrings中,并打印输出到控制台。
时间: 2024-03-21 10:42:41 浏览: 22
好的,这是一个比较基础的Java IO操作。下面是一个可能的实现方法:
```java
import java.io.*;
public class ArrayIO {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String[] cities = {"北京", "上海", "广州"};
// 序列化数组,写入文件
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("array.dat"))) {
oos.writeObject(numbers);
oos.writeObject(cities);
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化数组,从文件读取数据
int[] newNumbers = null;
String[] newCities = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("array.dat"))) {
newNumbers = (int[]) ois.readObject();
newCities = (String[]) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 打印输出新数组
if (newNumbers != null) {
for (int i : newNumbers) {
System.out.print(i + " ");
}
System.out.println();
}
if (newCities != null) {
for (String s : newCities) {
System.out.print(s + " ");
}
System.out.println();
}
}
}
```
这个程序首先定义了两个数组 `numbers` 和 `cities`,然后使用 `ObjectOutputStream` 将这两个数组序列化并写入文件 `array.dat` 中。接着,使用 `ObjectInputStream` 从文件中读取数据并反序列化成新的数组 `newNumbers` 和 `newCities`,最后打印输出这两个新数组的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)