Serialization is a process of converting an object into a byte stream, and Deserialization is a process of converting the serialized object back into a Java object.
When to use Serialization?
We use Serialization when we need to:
- Write an object to a file and store it on a disk.
- Send data over the network.
- Save an object state on disk, e.g., in the middle of some process, so that we can deserialize it and continue where we left.
Serialization and Deserialization are platform-independent, so we can serialize an object in one platform and deserialize it in other.
For a class to be serializable, it must implement a Serializable interface.
Serialization in Java
Let’s write a User class that implements a Serializable interface.
import java.io.Serializable; public class User implements Serializable { int userId; String name; public User(int userId, String name) { this.userId = userId; this.name = name; } }
Now, let’s serialize an object of the User class. We will use the writeObject() method of ObjectOutputStream class to serialize and save the object’s state in the file named user1.txt.
import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class Test { public static void main(String args[]) { try { User user1 = new User(15, "Ryan"); //Write the object in a stream FileOutputStream outputStream = new FileOutputStream("user1.txt"); ObjectOutputStream out = new ObjectOutputStream(outputStream); out.writeObject(user1); out.flush(); // close the stream out.close(); } catch (Exception e) { System.out.println("Writing object to file failed. Message: " + e.getMessage()); } } }
We have successfully written the object state into a file user1.txt.
Now let’s deserialize it back to the Java object.
Deserialization in Java
Let’s read the User object from a file user1.txt and convert it back to the Java object. We will use the readObject() of ObjectInputStream class.
import java.io.* public class Test { public static void main(String args[]) { try { //Read the object ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("user1.txt")); User user1 = (User) inputStream.readObject(); System.out.println("User object:"); System.out.println(user1.userId + " " + user1.name); //close the stream inputStream.close(); } catch (Exception e) { System.out.println("Reading object from a file failed. Message: " + e.getMessage()); } } }
I hope this tutorial was helpful to you. You now know how to use serialization and deserialization in Java. And if you are interested in more examples, then have a look at how to serialize and deserialize Array in Java.
Happy coding!