Java实现对象的序列化和反序列化
时间: 2024-03-02 07:44:51 浏览: 33
Java中对象的序列化和反序列化可以通过实现Serializable接口来实现。下面是一个简单的例子:
```java
import java.io.*;
public class SerializationDemo {
public static void main(String[] args) {
// 创建一个Person对象
Person person = new Person("Tom", 20);
// 将Person对象序列化到文件中
try {
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in person.ser");
} catch (IOException i) {
i.printStackTrace();
}
// 从文件中反序列化Person对象
try {
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
person = (Person) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Person class not found");
c.printStackTrace();
return;
}
// 输出反序列化后的Person对象
System.out.println("Deserialized Person...");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
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;
}
}
```
上述代码中,我们首先创建了一个Person对象,然后将其序列化到文件中。接着,我们从文件中反序列化Person对象,并输出其属性值。