Java学习笔记:序列化和反序列化

 注: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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值