zoukankan      html  css  js  c++  java
  • java 序列化与解序列化

    小例

    import java.io.*;
    public class Box implements Serializable{
        private int width;
        private int height;
        public void setWidth(int w){
            width = w;
        }
        public void setHeight(int h){
            height = h;
        }
        public int getWidth(){
            return width;
        }
        public int getHeight(){
            return height;
        }
        public static void main(String[] args){
            Box myBox = new Box();
            myBox.setWidth(20);
            myBox.setHeight(100);
    
            try {
                FileOutputStream fs = new FileOutputStream("foo.ser");
                ObjectOutputStream os = new ObjectOutputStream(fs);
                os.writeObject(myBox);
                os.close();
            } catch (Exception ex){
                ex.printStackTrace();
            }
    
            myBox = null;
    
            try{
                FileInputStream fis = new FileInputStream("foo.ser");
                ObjectInputStream is = new ObjectInputStream(fis);
                Box readBox = (Box) is.readObject();
                System.out.println("Box Obj " + readBox.getWidth());
                System.out.println("Box Obj height:" + readBox.getHeight());
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    结果

    Box Obj 20
    Box Obj height:100
    

    图示

    序列化

    反序列化  

  • 相关阅读:
    BZOJ1049 [HAOI2006]数字序列0
    UOJ265 【NOIP2016】愤怒的小鸟
    #include <deque>
    #include <queue>
    #include <vector>
    #include <set>
    #include <map>
    BZOJ1217:[HNOI2003]消防局的设立
    浅谈贪心
    CF1060B:Maximum Sum of Digits
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/6582006.html
Copyright © 2011-2022 走看看