首页 > 其他 > 详细

序列化与反序列化

时间:2017-06-25 18:24:18      阅读:279      评论:0      收藏:0      [点我收藏+]

序列化:将对象写入文件,对象要继承serializable实现接口

private static void xulihua() {
        Student st = new Student();
        st.setId(1000);
        st.setName("测试");
        st.setSex("男");
        st.setHp(100);
        ObjectOutputStream oos = null;
        try {
            OutputStream os = new FileOutputStream("f:\\stu.dat");
            oos = new ObjectOutputStream(os);
            st.setHp(50);   
            System.out.println(".....保存游戏进度......");
            System.out.println("被弄死了......");
            System.out.println("Game over.....");
            oos.writeObject(st);
            oos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

反序列化:对象不能改变

private static void reload(){
        ObjectInputStream  ois=null;
        try {
            InputStream  in=new FileInputStream("f:\\stu.dat");
            ois=new ObjectInputStream(in);
            Student  stu=(Student) ois.readObject();
            System.out.println(stu.toString());
        } catch (FileNotFoundException e) { 
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) { 
            e.printStackTrace();
        }finally{
            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) { 
                    e.printStackTrace();
                }
            }
        }
    }

 

序列化与反序列化

原文:http://www.cnblogs.com/by-1642146903/p/7077369.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!