您当前的位置: 首页 >  Java

ITKEY_

暂无认证

  • 0浏览

    0关注

    732博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java温故而知新-序列化与反序列化

ITKEY_ 发布时间:2021-03-17 21:40:34 ,浏览量:0

Serializable接口

如果需要有序列化与反序列化支持必须实现这个接口。

代码
package com.itkey.javareview.温故知新.io;

import lombok.Data;

import java.io.*;

@Data
class Person implements Serializable {
    private String name;
    private int age;
    private String school;

    public Person(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }

}

public class 序列化与反序列化 {
    private static final File BINARY_FILE = new File("/Users/itkey/Documents/GitHub/java-review/src/main/java/com/itkey/javareview/温故知新/io" + File.separator+"person.ser");

    public static void main(String[] args) throws Exception{
        Person zxc = new Person("周星驰", 18, "不知道");
        System.out.println(zxc);
        System.out.println("-------序列化------");
        serial(zxc);

        System.out.println("-------反序列化------");
        Object result = deSerial();
        System.out.println(result);
    }

    /**
     * 序列化
     * @param obj
     */
    public static void serial(Object obj) throws Exception{
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(BINARY_FILE));
        oos.writeObject(obj);
        oos.close();
    }
    /**
     * 反序列化
     * @param
     */
    public static Object deSerial() throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(BINARY_FILE));
        Object obj = ois.readObject();
        ois.close();
        return obj;
    }
}

transient关键字

在这里插入图片描述 使用方法如下: private transient String school;

这样这个属性就不会被序列化了。

关注
打赏
1665243900
查看更多评论
立即登录/注册

微信扫码登录

0.0365s