Java之IO学习(二)对象操作(序列化、反序列化)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014252478/article/details/83547680

1、内容

序列化就是将对象转换成字节序列,方便存储和转换

ObjectInputStream--readObject(): 读入对象,反序列化
ObjectOutputStream--writeObject(): 输出对象,将对象转换为字节传输, 序列化

注意:这里序列化对静态变量无效,因为静态状态是属于类的状态

只有在写出对象时,才能用writeObject/readObject方法,对于基本类型,需要使用如writeInt/readInt或者writeouble/readDouble方法。(对象流类都实现了DataInput或者DataOutput)

2、序列化需要实现serializable接口(否则异常)

public static void main(String[] args) throws IOException, ClassNotFoundException {

    A a1 = new A(123, "abc");
    String objectFile = "file/a1";

    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
    objectOutputStream.writeObject(a1);
    objectOutputStream.close();

    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
    A a2 = (A) objectInputStream.readObject();
    objectInputStream.close();
    System.out.println(a2);
}

private static class A implements Serializable {

    private int x;
    private String y;

    A(int x, String y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "x = " + x + "  " + "y = " + y;
    }
}

3、transient可以使部分数据不序列化:

ArrayList 中存储数据的数组 elementData 是用 transient 修饰的,因为这个数组是动态扩展的,并不是所有的空间都被使用,因此就不需要所有的内容都被序列化。通过重写序列化和反序列化方法,使得可以只序列化数组中有内容的那部分数据。

private transient Object[] elementData;

猜你喜欢

转载自blog.csdn.net/u014252478/article/details/83547680