序列化和反序列化对象

被序列化的对象需要实现Serializable接口
例子:

class S implements Serializable {
        int a;
        int b;

        public S(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public int getA() {
            return a;
        }

        public void setA(int a) {
            this.a = a;
        }

        public int getB() {
            return b;
        }

        public void setB(int b) {
            this.b = b;
        }

        @Override
        public String toString() {
            return "S{" +
                    "a=" + a +
                    ", b=" + b +
                    '}';
        }
    }

序列化和反序列化操作

public static void main(String[] args) {
        // 序列化
        try {
            S s = new S(10, 20);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
            oos.writeObject(s);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
            S s = (S) ois.readObject();
            ois.close();
            System.out.println(s.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

结果:

S{a=10, b=20}

猜你喜欢

转载自blog.csdn.net/weixin_34067102/article/details/86822604