该流可以将一个对象写出, 或者读取一个对象到程序中. 也就是执行了序列化和反序列化的操作.
ObjectOutputStream new ObjectOutputStream(OutputStream), writeObject() public class Demo3_ObjectOutputStream { public static void main(String[] args) throws IOException { Person p1 = new Person("张三", 23); Person p2 = new Person("李四", 24); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));//创建对象输出流 oos.writeObject(p1); oos.writeObject(p2); oos.close(); } }
ObjectInputStream
new ObjectInputStream(InputStream), readObject()
public class Demo3_ObjectInputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt")); Person p1 = (Person) ois.readObject(); Person p2 = (Person) ois.readObject(); System.out.println(p1); System.out.println(p2); ois.close(); } }
对象操作流优化
Person p1 = new Person("张三", 23); Person p2 = new Person("李四", 24); Person p3 = new Person("马哥", 18); Person p4 = new Person("辉哥", 20); ArrayList<Person> list = new ArrayList<>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f.txt")); oos.writeObject(list); //写出集合对象 oos.close();