📅  最后修改于: 2023-12-03 15:31:31.676000             🧑  作者: Mango
Java ObjectOutputStream类是Java IO包中的一个类,用于将Java对象序列化成二进制流并将其写入输出流中,以实现对象的持久化和对象间的传输。
import java.io.*;
public class Main {
static class Person implements java.io.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;
}
}
public static void main(String[] args) {
String fileName = "person.ser";
// 序列化Person对象,并保存到文件中
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
Person person = new Person("Tom", 26);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in " + fileName);
} catch (IOException i) {
i.printStackTrace();
}
// 反序列化Person对象
try {
FileInputStream fileIn = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileIn);
Person person = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized data is: " + person.getName() + " " + person.getAge());
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Person class not found");
c.printStackTrace();
return;
}
}
}