序列化和反序列化
ObjectOutputStream 序列化 ObjectInputStream反序列化 序列化的类必须继承 Serializable; 不想序列化的属性可以加上transient static 用静态修饰符修饰 不会被序列化 因为序列化是把对象的数据持久化存储 而静态属于类加载的数据 不会被序列化 package cn.lijun.com; import java.io.Serializable; public class Person implements Serializable{ private String name; private int 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 + "]"; } public Person(String name, int age) { this.name = name; this.age = age; } } package cn.liju.demo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; // IO 流的对象 实现对IO流的序列化 和反序列化 public class Demo1ObjectStream { public static void main(String[] args) throws Exception { writeObject(); readObject(); } public static void readObject() throws Exception{ FileInputStream fos = new FileInputStream("c:\\person1.txt"); //创建反序列化流 readObject() 读对象 ObjectInputStream ois = new ObjectInputStream(fos); Object obj = ois.readObject(); System.out.println(obj); ois.close(); } public static void writeObject() throws Exception{ FileOutputStream fos = new FileOutputStream("c:\\person1.txt"); // 创建写出对象的序列化流的对象 构造方法传递字节输出流 ObjectOutputStream oos = new ObjectOutputStream(fos); Demo1Person p = new Demo1Person("朱东洋", 20); oos.writeObject(p); oos.close(); } }