Home > Java > javaTutorial > How to achieve persistence of objects using serialization and deserialization in Java?

How to achieve persistence of objects using serialization and deserialization in Java?

王林
Release: 2023-08-02 14:37:11
Original
1476 people have browsed it

How to use serialization and deserialization in Java to achieve object persistence?

Introduction:
In Java development, object persistence is an important way to achieve long-term storage of data. Serialization and deserialization are one of the commonly used ways to achieve object persistence in Java. This article will introduce the concepts of serialization and deserialization and how to use serialization and deserialization in Java to achieve object persistence.

1. What are serialization and deserialization?
Serialization is the process of converting an object into a byte stream so that the object can be copied and transmitted during operations such as network transmission or saving to disk. Deserialization is the process of re-converting a byte stream into an object and restoring the object's state and data. In Java, object serialization and deserialization is achieved by implementing the Serializable interface.

2. Serialization implementation methods
Java provides two main serialization methods, namely byte stream-based serialization and character stream-based serialization.

1. Serialization based on byte stream
Serialization based on byte stream can be implemented through the ObjectOutputStream and ObjectInputStream classes. The following is a sample code that demonstrates how to serialize and deserialize objects using a byte stream-based approach.

import java.io.*;

public class ByteStreamSerializationDemo {
    public static void main(String[] args) {
        // 将对象序列化为字节流
        try {
            // 创建一个待序列化的对象
            Person person = new Person("Tom", 30);
            
            // 创建一个输出流
            FileOutputStream fileOutputStream = new FileOutputStream("person.obj");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            
            // 将对象写入输出流
            objectOutputStream.writeObject(person);
            
            // 关闭输出流
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 将字节流反序列化为对象
        try {
            // 创建一个输入流
            FileInputStream fileInputStream = new FileInputStream("person.obj");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            
            // 读取对象数据
            Person person = (Person) objectInputStream.readObject();
            
            // 打印对象数据
            System.out.println(person.getName());   // 输出:Tom
            System.out.println(person.getAge());    // 输出:30
            
            // 关闭输入流
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Person implements Serializable {
    private String name;
    private int age;
    
    // 构造方法、getter和setter省略
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Copy after login

In the above code, we first create a Person object to be serialized, then serialize the object into a byte stream through the FileOutputStream and ObjectOutputStream classes, and write it to a file. Next, we deserialize the byte stream in the file into an object through the FileInputStream and ObjectInputStream classes, and finally print out the object's attribute values.

2. Character stream-based serialization
Character stream-based serialization can be implemented through the ObjectWriter and ObjectReader classes.

import java.io.*;

public class CharacterStreamSerializationDemo {
    public static void main(String[] args) {
        // 将对象序列化为字符流
        try {
            // 创建一个待序列化的对象
            Person person = new Person("Tom", 30);
            
            // 创建一个Writer
            FileWriter fileWriter = new FileWriter("person.txt");
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            ObjectWriter objectWriter = new ObjectWriter(bufferedWriter);
            
            // 将对象写入字符流
            objectWriter.writeObject(person);
            
            // 关闭字符流
            objectWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 将字符流反序列化为对象
        try {
            // 创建一个Reader
            FileReader fileReader = new FileReader("person.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            ObjectReader objectReader = new ObjectReader(bufferedReader);
            
            // 读取对象数据
            Person person = (Person) objectReader.readObject();
            
            // 打印对象数据
            System.out.println(person.getName());   // 输出:Tom
            System.out.println(person.getAge());    // 输出:30
            
            // 关闭字符流
            objectReader.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Person implements Serializable {
    private String name;
    private int age;
    
    // 构造方法、getter和setter省略
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Copy after login

In the above code, we serialize the object into a character stream through the FileWriter, BufferedWriter and ObjectWriter classes and write it to the file. Then, the character stream in the file is deserialized into an object through the FileReader, BufferedReader, and ObjectReader classes, and finally the object's attribute values ​​can be printed out.

3. Notes
When using serialization and deserialization in Java to achieve persistence of objects, you need to pay attention to the following points:

1. The class of the object must be implemented Serializable interface, otherwise serialization and deserialization cannot be performed.
2. All referenced objects within the serialized class must also be serializable.
3. The fields of serialized and deserialized classes can be of any type, including custom classes, basic data types, collection types, etc.
4. Fields of serialized and deserialized classes can be transient-modified, and they will not be persisted.

Conclusion:
Through the introduction of this article, we have learned what serialization and deserialization are, and demonstrated through code examples how to use serialization and deserialization in Java to achieve object persistence. . In actual development, long-term storage and transmission of objects can be achieved by selecting a suitable serialization method according to needs and following serialization specifications and precautions.

The above is the detailed content of How to achieve persistence of objects using serialization and deserialization in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template