什么是 java 序列化?什么情况下需要序列化?序列化的代码示例
时间: 2023-06-01 17:05:16 浏览: 87
Java序列化是指将一个对象转换成一个字节流,以便可以将其存储在文件中、通过网络传输或在进程之间传递。序列化可以用来保存对象的状态,以便可以在以后的时间重建该对象,而无需重新创建它。需要序列化的情况包括:网络传输,对象持久化,进程之间通信等。
以下是Java序列化的代码示例:
```java
import java.io.*;
public class SerializationDemo {
public static void main(String[] args) {
// Serialize object
Student student = new Student("Tom", "M", 23);
try {
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(student);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in student.ser file");
} catch (IOException i) {
i.printStackTrace();
}
// Deserialize object
try {
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Student deserializedStudent = (Student) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized data:");
System.out.println("Name: " + deserializedStudent.getName());
System.out.println("Gender: " + deserializedStudent.getGender());
System.out.println("Age: " + deserializedStudent.getAge());
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Student class not found");
c.printStackTrace();
}
}
}
class Student implements Serializable {
private String name;
private String gender;
private int age;
public Student(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
}
```
阅读全文