码迷,mamicode.com
首页 > 其他好文 > 详细

序列化与反序列化

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

标签:log   tput   写入   stack   反序   cto   stream   serial   ace   

序列化:将对象写入文件,对象要继承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();
                }
            }
        }
    }

 

序列化与反序列化

标签:log   tput   写入   stack   反序   cto   stream   serial   ace   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!