怎么将java实体类序列号
时间: 2023-05-28 11:02:16 浏览: 65
要将Java实体类进行序列化,需要实现Serializable接口。这个接口没有任何方法,只是一个标记接口,表示该类可以被序列化和反序列化。
下面是一个示例代码:
```
import java.io.Serializable;
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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
实现了Serializable接口后,就可以进行序列化操作了。下面是一个将Person对象写入文件的示例代码:
```
Person person = new Person("张三", 20);
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(person);
objectOut.close();
fileOut.close();
```
读取文件并反序列化为Person对象:
```
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
Person person = (Person) objectIn.readObject();
objectIn.close();
fileIn.close();
```
需要注意的是,序列化和反序列化时需要捕获IOException和ClassNotFoundException异常。序列化后的文件不可读,只能使用ObjectInputStream读取。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)