首页 > 代码库 > 序列化与反序列化

序列化与反序列化

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

 

序列化与反序列化