注:Students类需要自己重新创建
单对象序列化
public class ObjectInputStreamTest01 { public static void main(String[] args) throws Exception{ ObjectInputStream ois =new ObjectInputStream(new FileInputStream("students")); //开始反序列化,读 Object obj = ois.readObject(); System.out.println(obj); //关闭 ois.close(); } }
单对象反序列化
public static void main(String[] args) throws Exception { Students s=new Students(111,"zhangsan"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students")); //序列化对象 oos.writeObject(s); //刷新 oos.flush(); //关闭 oos.close(); }
多个对象序列化,可以把对象放在集合里面,然后序列化集合
public static void main(String[] args) throws Exception { List<Students> studentsList = new ArrayList<>(); studentsList.add(new Students(1, "zhangsan")); studentsList.add(new Students(2, "lisi")); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student2")); //序列化一个集合,这个集合中放了很多其他对象 oos.writeObject(studentsList); oos.flush(); oos.close(); }
多个对象反序列化
public static void main(String[] args) throws Exception{ ObjectInputStream s2 = new ObjectInputStream(new FileInputStream("student2")); // Object ois2 =s2.readObject(); List<Students> ois2 = (List<Students>)s2.readObject(); //System.out.println(ois2); //然后for循环 for(Students studnt3: ois2){ System.out.println(studnt3); } s2.close(); }