JAVA的序列化与反序列化(一)

序列化

序列化是一种对象持久化的手段。通常我们在jvm平台创建对象。但是仅仅当jvm正在运行时,对象才会存在。也就是说,当java运行停止之后,这个对象所保存的信息也就消失了。那么当我们需要保存一个java对象的信息,并需要的时候又可以把他取出来。java的序列化就可以帮我们实现。
我们对Java对象进行序列化的时候,会把其状态保存为一组字节,当我们需要的时候,又将其取出来。必须注意地是,对象序列化保存的是对象的”状态”,即它的成员变量 那么也就是说,对象序列化不会关注类中的静态变量

如何进行序列化

在Java中想要实现序列化很简单 只需要实现一个Serializable接口即可
序列化接口没有方法或字段,仅用于标识可序列化的语义

public class Product implements Serializable {
    private String name;
    private double price;
    private String describe;

    public Product() {
    }

    public Product(String name, double price, String describe) {
        this.name = name;
        this.price = price;
        this.describe = describe;
    }
    .....部分代码省略

下面进行序列化和反序列化操作

所需要用到主要类有:
ObjectOutputStream
ObjectInputStream

/**
 * @author hao
 * @create 2019-09-03 ${TIM}
 * //测试java对象的序列化 与反序列化 
 */
public class SerialazableDemoTest1 {
    public static void main(String[] args) {
        Product product = new Product("电视机",3900.00,"这是一台高清");
        System.out.println("序列化之前"+product);
        // 序列化
        ObjectOutputStream  out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream("D:\\a\\tempFile"));
            out.writeObject(product);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //反序列化
        ObjectInputStream in = null;
        Product pro = null;
        try {
            in = new ObjectInputStream(new FileInputStream("D:\\a\\tempFile"));
            //反序列读取
            pro = (Product) in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println("反序列化之后"+pro);


    }
}
输出:
序列化之前Product{name='电视机', price=3900.0, describe='这是一台高清'}
反序列化之后Product{name='电视机', price=3900.0, describe='这是一台高清'}

然后我们进入序列化的文件夹 如图所示:

在这里插入图片描述
这个文件也就是我们序列化对象之后的文件。
我们使用ObjectOutputStream和ObjectInputStreamwriteObject方法把一个对象进行持久化。再使用ObjectInputStream的readObject从持久化存储中把对象读取出来。当我们不想序列化某个字段时 使用transient关键字,标识该字段

总结:

1、如果一个类想被序列化,需要实现Serializable接口。否则将抛出NotSerializableException异常。(至于为什么将在下一篇文章中介绍)

发布了98 篇原创文章 · 获赞 44 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43732955/article/details/100512943