Java Serialization examples

In Java, Serialization means convert an object into a byte stream, which can be saved into a file or transferred over the network, and the Deserialization is the reverse.

Serialization example.


    // Save object into a file.
    public static void writeObject(Object obj, File file) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(obj);
            oos.flush();
        }
    }

Deserialization example.


    // Get object from a file.
    public static Object readObject(File file) throws IOException, ClassNotFoundException {
        Object result = null;
        try (FileInputStream fis = new FileInputStream(file);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            result = ois.readObject();
        }
        return result;
    }

1. POJO

Review a simple Person class, implements Serializable.

Person.java

package com.mkyong.io.object;

import java.io.Serializable;
import java.math.BigDecimal;

public class Person implements Serializable {

    // optional, if missing, JVM will create it.
    // better declare as a version control.
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    // dun save this field into file
    private transient BigDecimal salary;

    // getters, setters, toString, constructor

}

In Java, an object that needs to serialize must implement the Serializable interface, else hits the below error.

Terminal

Exception in thread "main" java.io.NotSerializableException: com.mkyong.io.object.Person

  at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)
  at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
  at com.mkyong.io.object.ObjectUtils.writeObject(ObjectUtils.java:14)
  at com.mkyong.io.object.ObjectUtils.main(ObjectUtils.java:35)

2. Java Serialization examples

See comments for self-explanatory.

ObjectUtils.java

package com.mkyong.io.object;

import java.io.*;
import java.math.BigDecimal;

// serialization and deserialization
public class ObjectUtils {

    // Serialization
    // Save object into a file.
    public static void writeObject(Person obj, File file) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(obj);
            oos.flush();
        }
    }

    // Deserialization
    // Get object from a file.
    public static Person readObject(File file) throws IOException, ClassNotFoundException {
        Person result = null;
        try (FileInputStream fis = new FileInputStream(file);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            result = (Person) ois.readObject();
        }
        return result;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Person person = new Person("mkyong", 40, new BigDecimal(900));

        // object -> file
        ObjectUtils.writeObject(person, new File("person.obj"));

        // file to object
        Person obj = ObjectUtils.readObject(new File("person.obj"));
        System.out.println(obj);

    }
}

Output

Terminal

Person{name='mkyong', age=40, salary=null}

What is transient?
Why is the salary null? During serialization, JVM ignores all transient fields. If we need to exclude specific object’s fields during serialization, mark it as transient.

3. What is serialVersionUID?

If the serialVersionUID is missing, the JVM will create it automatically. The serialVersionUID is something like version number; in short, if we save an object with 1L, we need to provide the same 1L to read the object, else hits an incompatible error.

Person.java

public class Person implements Serializable {

    private static final long serialVersionUID = 1L;
    //...
}

For example, we saved an object with serialVersionUID = 1L into a file name person.obj. Later we add or delete some fields from the object, and update serialVersionUID to 2L. Now, read the person.obj file and try to convert it back to the modified object, since both serialVersionUID is different, we will hit the following incompatible error:

Terminal

Exception in thread "main" java.io.InvalidClassException: com.mkyong.io.object.Person;

  local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2

	at java.base/java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:689)
	at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1903)
	at java.base/java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1772)
	at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2060)
	at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1594)
	at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
	at com.mkyong.io.object.ObjectUtils.readObject(ObjectUtils.java:25)
	at com.mkyong.io.object.ObjectUtils.main(ObjectUtils.java:38)  

Download Source Code

$ git clone https://github.com/mkyong/core-java.git

$ cd java-io

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar