序列化 1.javaBean类实现Serializable接口
public class Empty implements Serializable { private String name; private int age; private String address; public Empty(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } @Override public String toString() { return "Empty{" + "name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Empty() { } public void eat() { System.out.println("chifan"); } }
2.序列化
public class Test { //序列化 public static void main(String[] args) throws IOException { //创建要序列化的对象 Empty empty = new Empty("张三",16,"天上人间"); //用输出流向文件中写数据 FileOutputStream fos = new FileOutputStream("E:\\a\\emp.ser"); //作用:把对象转成字节数据的输出到文件中保存,对象的输出过程称为序列化,可实现对象的持久存储。 ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(empty); } }
3.反序列化
public class Test_2 { public static void main(String[] args) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream("E:\\a\\emp.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Object o = ois.readObject(); System.out.println(o); } }