Easy Tutorial
❮ Java Mysql Connect File Dir ❯

Java Serialization

Java provides a mechanism for object serialization, where an object can be represented as a sequence of bytes, which includes the object's data, information about the object's type, and the types of data stored in the object.

After writing the serialized object to a file, it can be read from the file and deserialized. This means that the object's type information, data, and data types can be used to create a new object in memory.

The entire process is independent of the Java Virtual Machine (JVM), meaning that an object serialized on one platform can be deserialized on a completely different platform.

The classes ObjectInputStream and ObjectOutputStream are high-level data streams that contain methods for deserializing and serializing objects.

The ObjectOutputStream class includes many write methods for various data types, but one special method is:

public final void writeObject(Object x) throws IOException

This method serializes an object and sends it to the output stream. Similarly, the ObjectInputStream class includes the following method for deserializing an object:

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next object from the stream and deserializes it. Its return value is of type Object, so you need to cast it to the appropriate data type.

To demonstrate how serialization works in Java, I will use the Employee class mentioned in previous tutorials. Assume we have defined the following Employee class, which implements the Serializable interface.

Employee.java File Code:

public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name + " " + address);
   }
}

Note that for an object of a class to be successfully serialized, two conditions must be met:

If you want to know if a standard Java class is serializable, check its documentation. It is simple to determine if an instance of a class can be serialized; just check if the class implements the java.io.Serializable interface.


Serializing an Object

The ObjectOutputStream class is used to serialize an object. The following SerializeDemo example instantiates an Employee object and serializes it to a file.

After running this program, an file named employee.ser is created. The program does not produce any output, but you can understand its function by reading the code.

Note: When serializing an object to a file, it is a standard convention in Java to give the file a .ser extension.

SerializeDemo.java File Code:

import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
      }
      catch(IOException i)
      {
         i.printStackTrace();
      }
   }
}
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch(IOException i) {
    i.printStackTrace();
}

Deserializing an Object

The following DeserializeDemo program demonstrates deserialization, where the Employee object is stored in /tmp/employee.ser.

DeserializeDemo.java File Code:

import java.io.*;

public class DeserializeDemo {
   public static void main(String [] args) {
      Employee e = null;
      try {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      } catch(IOException i) {
         i.printStackTrace();
         return;
      } catch(ClassNotFoundException c) {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
   }
}

The above program compiles and runs with the following output:

Deserialized Employee...
Name: Reyan Ali
Address: Phokka Kuan, Ambehta Peer
SSN: 0
Number: 101

Here are some key points to note:

The try/catch block in the readObject() method attempts to catch a ClassNotFoundException. For the JVM to deserialize an object, it must be able to find the bytecode for the class. If the JVM cannot find the class during the deserialization process, it throws a ClassNotFoundException.

Note that the return value of the readObject() method is cast to an Employee reference.

When the object was serialized, the SSN attribute had a value of 111222333, but since it is transient, the value was not sent to the output stream. Therefore, the SSN attribute of the deserialized Employee object is 0.

❮ Java Mysql Connect File Dir ❯