package com.wzy.main; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; @SuppressWarnings("serial") class Person implements Serializable{ public Person(String name,Integer id,Integer age) { this.id = id; this.name = name; this.age = age; } private String name; private Integer id; private transient Integer age;//transient属性不会被序列化 @Override public String toString() { return "name:"+name+", id:"+id+", age:"+age; } } public class Test02 { public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { /** * 需要被序列化的对象继承Serializable标识接口,表示此对象有可以被序列化的能力 * 序列化,将一个对象以二进制的形式保存到磁盘上 * 反序列化,从磁盘上读取文件返回此对象 * */ ser(new Person("tom",10001,45));//序列化 dser();//反序列化 } static void ser(Person p) throws FileNotFoundException, IOException{ ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("E:"+File.separator+"person")); out.writeObject(p); out.close(); System.out.println("对象已被保存到本地"); } static void dser() throws FileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream in = new ObjectInputStream( new FileInputStream("E:"+File.separator+"person")); Person p = (Person)in.readObject(); in.close(); System.out.println(p.toString()); } }