使用序列化和反序列化实现person对象的存储和读。将序列化生产的二进制文件存为d:\\person.bin,并利用反序列化读出文件内容,输出到控制台中。
时间: 2023-07-18 18:14:21 浏览: 58
好的,以下是实现的示例代码:
```java
import java.io.*;
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
// 创建Person对象
Person person = new Person("张三", 20);
// 序列化Person对象
try {
FileOutputStream fos = new FileOutputStream("d:\\person.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
fos.close();
System.out.println("Person对象已序列化并保存到d:\\person.bin文件中");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化Person对象
try {
FileInputStream fis = new FileInputStream("d:\\person.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
Person personDeserialized = (Person) ois.readObject();
ois.close();
fis.close();
System.out.println("从d:\\person.bin文件中读取到的Person对象:");
System.out.println("姓名:" + personDeserialized.getName());
System.out.println("年龄:" + personDeserialized.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
运行该程序后,控制台输出如下:
```
Person对象已序列化并保存到d:\person.bin文件中
从d:\person.bin文件中读取到的Person对象:
姓名:张三
年龄:20
```
说明已经成功地将Person对象序列化并保存到了d:\person.bin文件中,并且能够通过反序列化将其读取出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)