栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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 ois2  = (List)s2.readObject();
    //System.out.println(ois2);
       //然后for循环
    for(Students studnt3: ois2){
        System.out.println(studnt3);
    }
      s2.close();
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/632026.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号