import java.io.*;
// 定义一个实现了 Serializable 接口的类
class Person implements Serializable {
private static final long serialVersionUID = 1L; // 序列化版本UID
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class SerializationExample {
// 序列化对象到文件
public static void serializeObject(Person person, String fileName) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
oos.writeObject(person);
System.out.println("对象已序列化并保存到文件: " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
// 从文件中反序列化对象
public static Person deserializeObject(String fileName) {
Person person = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
person = (Person) ois.readObject();
System.out.println("对象已从文件 " + fileName + " 反序列化");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return person;
}
public static void main(String[] args) {
Person person = new Person("张三", 30);
// 序列化对象
serializeObject(person, "person.ser");
// 反序列化对象
Person deserializedPerson = deserializeObject("person.ser");
if (deserializedPerson != null) {
System.out.println("反序列化后的对象: " + deserializedPerson);
}
}
}
Person
类:
Serializable
接口,表示该类的对象可以被序列化。serialVersionUID
是序列化版本UID,用于确保序列化和反序列化时类结构的一致性。serializeObject
方法:
ObjectOutputStream
将 Person
对象写入到指定的文件中。deserializeObject
方法:
ObjectInputStream
从文件中读取 Person
对象,并返回该对象。main
方法:
Person
对象,并调用 serializeObject
方法将其序列化到文件中。deserializeObject
方法从文件中读取并反序列化对象,最后打印出反序列化后的对象信息。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站