java序列化和反序列化
时间: 2023-10-30 10:14:43 浏览: 36
Java序列化是将对象转换为字节流的过程,以便将其存储在文件中或通过网络发送。反序列化则是将字节流转换回对象的过程。
要使一个类可序列化,需要实现Serializable接口。该接口不包含任何方法,只是用来标识一个类可以被序列化。
下面是一个简单的例子,演示如何序列化和反序列化一个对象:
```
import java.io.*;
public class SerializationDemo {
public static void main(String[] args) {
// 创建一个对象
Student student = new Student("Tom", 18);
// 序列化对象到文件中
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
out.writeObject(student);
System.out.println("Serialized data is saved in student.ser");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化对象
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student newStudent = (Student) in.readObject();
System.out.println("Deserialized data:");
System.out.println("Name: " + newStudent.getName());
System.out.println("Age: " + newStudent.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
运行结果如下:
```
Serialized data is saved in student.ser
Deserialized data:
Name: Tom
Age: 18
```
在这个例子中,我们创建了一个Student类,并实现了Serializable接口。然后我们创建了一个Student对象并将其序列化到文件student.ser中。最后我们从文件中反序列化对象,并打印出其属性值。
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)