序列化
@Test public void test14() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object1.dat")); oos.writeObject(new Person("张三", 20)); oos.close(); }
反序列化
@Test public void test15() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object1.dat")); Person p = (Person) ois.readObject(); System.out.println(p); ois.close(); }
自定义的Person类。
1.实现Serializable接口,
2.提供序列版本号serialVersionUID,
3.类的属性也必须是可序列化的。
4.其中static(类所有)和transient修饰的属性不会被序列化。
package com.atguigu.java.pojo; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 487667876562L; private String name; private int age; public Person() { } 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; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
原文地址:https://www.cnblogs.com/noyouth/p/11751208.html
时间: 2024-10-06 01:10:17