Java file operation & object serialization and deserialization Store the object in the file and then take it out

1 Introduction

Data objects in memory can only be persisted or transmitted over the network when they are converted into binary streams. The process of converting objects into binary streams is called serialization; on the contrary, the process of restoring binary streams to data objects is called reverse Serialization (Deserialization).

2) Serialization and deserialization code implementation

First serialize the object to disk, and then deserialize the object from the disk, please refer to the following code:

class SerializableTest {
    
    
    public static void main(String[] args) throws IOException, ClassNotFoundException {
    
    
        // 对象赋值
        User user = new User();
        user.setName("老王");
        user.setAge(30);
        System.out.println(user);
        // 创建输出流(序列化内容到磁盘)
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.out"));
        // 序列化对象
        oos.writeObject(user);
        oos.flush();
        oos.close();
        // 创建输入流(从磁盘反序列化)
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.out"));
        // 反序列化
        User user2 = (User) ois.readObject();
        ois.close();
        System.out.println(user2);
    }
}
class User implements Serializable {
    
    
    private static final long serialVersionUID = 3831264392873197003L;
    private String name;
    private int age;
    @Override
    public String toString() {
    
    
        return "{name:" + name + ",age:" + age + "}";
    }
    // setter/getter...
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    public int getAge() {
    
    
        return age;
    }
    public void setAge(int age) {
    
    
        this.age = age;
    }
}

Program execution result:

{
    
    name:老王,age:30}
{
    
    name:老王,age:30}

Guess you like

Origin blog.csdn.net/weixin_43158695/article/details/114082189