Serialization is the process of saving an object’s states in a persistent format (such as file stream or database), and later restoring them back from the stream (de-serialization). In Java, an object of a class is serializable if the class implements the java.io.Serializable interface. This is a marker interface which tells the JVM that the class is eligible for serialization. In this article, we’ll learn how to serialize and de-serialize a simple Java object.

First, let’s create an object model class (User.java) as follows:

package net.codejava.io;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

	private static final long serialVersionUID = 1234L;

	private String username;
	private String email;
	private transient String password;
	private Date birthday;
	private int age;

	public User(String username, String email, String password, Date birthday,
			int age) {
		this.username = username;
		this.email = email;
		this.password = password;
		this.birthday = birthday;
		this.age = age;
	}

	public void printInfo() {
		System.out.println("username: " + username);
		System.out.println("email: " + email);
		System.out.println("password: " + password);
		System.out.println("birthday: " + birthday);
		System.out.println("age: " + age);
	}

	// getters and setters

}

 

There are three important points in this model class:

  • It must implements the Serializable interface. Otherwise, we’ll get a java.io.NotSerializableException when trying to serialize an object of the class.
  • A constant named serialVersionUID  is declared and assigned a long value:
    private static final long serialVersionUID = 1234L;

    This is a conventional constant which should be declared when a class implements the Serializable interface. The serial version UID strongly ensures compatibility between the serialized and de-serialized versions of objects of a class, because the process of serialization and de-serialization can happen on different computers and systems. Although this declaration is optional, it’s always recommended to declare the serialVersionUID for a serializable class.

  • Notice that the password field is marked as transient:
    private transient String password;

    Because we don’t want store the password when serializing the object. The rule is, when a variable is marked as transient, its object won’t be serialized during serialization.

     

Now, let’s look at some examples of how to serialize an object of the above User class to a file stream, and then de-serialize it from the file. 

 

Java Serialization Example:

The following method serializes an object of type User to a file stream specified by the given filePath:

static void serialize(User user) {
	try {
		FileOutputStream fos = new FileOutputStream(filePath);
		ObjectOutputStream outputStream = new ObjectOutputStream(fos);
		outputStream.writeObject(user);
		outputStream.close();
	} catch (IOException ex) {
		System.err.println(ex);
	}
} 

 

Java De-serialization Example:

The following method reads a file given by the filePath and de-serializes the stored User object:

static User deserialize() {
	User savedUser = null;

	try {
		FileInputStream fis = new FileInputStream(filePath);
		ObjectInputStream inputStream = new ObjectInputStream(fis);
		savedUser = (User) inputStream.readObject();
		inputStream.close();
	} catch (IOException | ClassNotFoundException ex) {
		System.err.println(ex);
	}

	return savedUser;
}  

 

Java Serialization Complete example program:

By combining the above two methods, we have a complete program as follows:

package net.codejava.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * This program demonstrates how to serialize and de-serialize a Java object.
 * @author www.codejava.net
 *
 */
public class BasicSerializationExample {
	static final String filePath = "user.ser";
	
	static void serialize(User user) {
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			ObjectOutputStream outputStream = new ObjectOutputStream(fos);
			outputStream.writeObject(user);
			outputStream.close();
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
	
	static User deserialize() {
		User savedUser = null;
		
		try {
			FileInputStream fis = new FileInputStream(filePath);
			ObjectInputStream inputStream = new ObjectInputStream(fis);
			savedUser = (User) inputStream.readObject();
			inputStream.close();
		} catch (IOException | ClassNotFoundException ex) {
			System.err.println(ex);
		}
		
		return savedUser;
	}
	
	public static void main(String[] args) {
		String username = "codejava";
		String email = "info@codejava.net";
		String password = "secret";
		Date birthDay = new Date();
		int age = 20;
		
		User newUser = new User(username, email, password, birthDay, age);
		
		serialize(newUser);

		User savedUser = deserialize();
		
		if (savedUser != null) {
			savedUser.printInfo();
		}
	}
} 

When running this program, the object state is stored in a file called “user.ser”, and the output would be as follows:

username: codejava
email: info@codejava.net
password: null
birthday: Wed Sep 11 15:25:01 ICT 2013
age: 20 

As we see, all the fields of the User object are saved and restored back perfectly, except the password field is null, because we mark it as transient.

 

Related Tutorials:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (BasicSerializationExample.java)BasicSerializationExample.java[Example program]1 kB
Download this file (User.java)User.java[Model class]1 kB

Add comment

   


Comments 

#1ABC2019-04-12 05:17
I am getting an error "System cannot find the path specified "
I used the full directory path of the file with the file name and ext. as an argument for FileOutputStream
I am using NetBeans IDE 8.2
Quote