public class Test6 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
User zs = new User("zs", 1);
write(zs);
User user = (User) read();
System.out.println(zs);
System.out.println(user);
System.out.println(zs==user);
}
static void write(Object o) throws IOException {
ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream("f://object.txt"));
outputStream.writeObject(o);
outputStream.flush();
outputStream.close();
}
static Object read() throws IOException, ClassNotFoundException {
ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream("f://object.txt"));
Object o = inputStream.readObject();
inputStream.close();
return o;
}
}
class User implements Serializable {
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
@Serial
private void writeObject(ObjectOutputStream outputStream) throws IOException {
// 需要序列化的对象属性
System.out.println("自定义write...");
outputStream.writeObject(name);
outputStream.writeInt(age);
}
@Serial
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
// 需要反序列化的属性,和写出时的顺序一致
System.out.println("自定义read...");
this.name= (String) inputStream.readObject();
this.age=(Integer) inputStream.readInt();
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
自定义对象的序列化和反序列化(readObject-writeObject)
文章介绍了如何在Java中使用序列化(writeObject)和反序列化(readObject)实现User类的对象持久化,通过ObjectOutputStream和ObjectInputStream操作文件object.txt。
摘要由CSDN通过智能技术生成