Serialization and deserialization of java objects

What are serialization and deserialization

When two processes communicate remotely, they can send various types of data to each other. No matter what type of data, it will be transmitted on the network in the form of binary sequence. For example, we can send string information through http protocol; We can also send Java objects directly on the network. The sender needs to convert the Java object into a byte sequence before it can be transmitted on the network; The receiver needs to restore the byte sequence to a Java object before it can be read normally.
The process of converting Java objects into byte sequences is called object serialization. The process of restoring byte sequences to Java objects is called object deserialization.

Object serialization has the following two functions:

  • Persistence: to permanently save the byte sequence of an object to the hard disk, usually in a file.
  • Network communication: a sequence of bytes that transfers objects over a network. For example, data communication and object transfer between servers. (transmission of objects between Message Oriented Middleware)

Classes and interfaces involved in serialization

  • ObjectOutputStream represents the object output stream. Its writeObject(Object obj) method can serialize the obj object specified by the parameter and write the resulting byte sequence to a target output stream.
  • ObjectInputStream represents the object input stream. Its readObject() method reads byte sequences from a source input stream, deserializes them into an object, and returns them.
    Only objects of classes that implement the Serializable interface can be serialized. The Serializable interface is an empty interface that only serves as a marker.

Operation object

Serialize object to file

ObjectOutputStream can write a Java object in memory to a file on disk by serialization. The serialized object must implement the Serializable serialization interface, otherwise an exception will be thrown.

Define entity class objects
package com.io;

import java.io.Serializable;

public class Users implements Serializable {
    private int userId;
    private String userName;
    private String userAge;

    public Users() {
    }

    public Users(int userId, String userName, String userAge) {
        this.userId = userId;
        this.userName = userName;
        this.userAge = userAge;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }
}

Object serialization
package com.io;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * The process of object serialization is to convert the object into bytes
 */
public class ObjectOutputStreamObjectTypeDemo {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;

        try {
            oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("/Users/pain_/Desktop/b/c/b")));
            Users user = new Users(1, "kevin", "18");
            oos.writeObject(user);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Object deserialization
package com.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * Object deserialization: byte to object
 */
public class ObjectInputStreamObjectTypeDemo {
    public static void main(String[] args) {
        ObjectInputStream ois = null;

        try {
            ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("/Users/pain_/Desktop/b/c/b")));
            Users users = (Users) ois.readObject();
            System.out.println("Id:" + users.getUserId() + "\t" + "full name:" + users.getUserName() + "\t" + "Age" + users.getUserAge());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Tags: Java

Posted by DavidT on Thu, 14 Apr 2022 10:35:40 +0930