Java Serialization Example


After knowing what is serialization and the classes available supporting serialization, let us write a program where a Student object is serialized, Student objects are written to a file and later read from the file. In this program, usage of access modifier "transient keyword" is illustrated (observe, the string address variable in the next program).

The Serialization example includes three programs.

1. Student.java : This class is serialized.
2. StudentWrite.java : This program creates some Student objects with some properties and writes to a file.
3. StudentRead.java : This program reads the Student objects from the file and print their properties.

Serialization Example: 1st Program File Name: Student.java

The Student class is serialized. The Student can be given properties like roll number, name, marks and address.

import java.io.*;                          // for Serializable interface

public class Student implements Serializable
{
  int rollNumber; 
  String name;
  double marks;
  transient String address;                // observe, transient keyword
                                           // constructor to assign properties
  public Student(int rollNumber, String name, double marks, String address)
  {
    this.rollNumber = rollNumber;
    this.name = name;
    this.marks = marks;
    this.address = address;
  }                                        // getter methods to retrieve properties
  public int getRollNumber( )
  {
    return rollNumber;
  }
  public String getName( )
  {
    return name;
  }
  public double getMarks( )
  {
    return marks;
  }
  public String getAddress( )
  {
    return address;
  }
}

The above code is very simple. Through constructor, properties for a student can be given and getter methods are used to retrieve the properties.

Observe, the address variable is declared transient. We discuss this in StudentRead.java, the third program.

Serialization Example: 2nd Program File Name: StudentWrite.java

In this program, some Student objects are created, assigned them with properties and later written to a text file, say, abc.txt.

import java.io.*;

public class StudentWrite
{
  public static void main(String args[]) throws Exception
  {
    FileOutputStream fos = new FileOutputStream("abc.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    Student std1 = new Student(35, "SNRao", 60.5, "Ameerpet, Hyderabad");
    Student std2 = new Student(45, "Jyostna", 70.5, "Paradise circle, Secunderabad");
    Student std3 = new Student(55, "Srinivas", 80.5, "Punjagutta, Hyderabad");

    oos.writeObject(std1);
    oos.writeObject(std2);
    oos.writeObject(std3);
		                         // writing anonymous Student object 
    oos.writeObject(new Student(65, "Jyothi", 90.5, "Kookatpally, Hyderabad"));

    fos.close();
    oos.close();
  }
}

We are using here, writeObject() method of ObjectOutputStream class. Three Student objects std1, std2, std3 and one anonymous object are written to a file, abc.txt.

Serialization Example: 3rd Program File Name: StudentRead.java

This program reads all the Student objects from the file abc.txt and prints their properties.

import java.io.*;
public class StudentRead
{
  public static void main(String args[]) throws Exception
  {
    FileInputStream fis = new FileInputStream("abc.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);

    while(true)
    {
      try
      {
        Student st = (Student) ois.readObject( );
        System.out.println(st.getRollNumber() + ", " + st.getName( ) + ", " + st.getMarks( ) + ", " + st.getAddress());
      }
      catch(EOFException e)
      {
        break;
      }
    } 

    ois.close(); 	
    fis.close();
  }
}


Serialization Example
Serialization Example: Screenshot when executed first "StudentWrite" and then "StudentRead"

Student st = (Student) ois.readObject();

The above statement can be split into two as follows.

Object obj = ois.readObject();
Student st = (Student) obj;

This while loop is a good programming technique when the number Student objects are not known (ofcourse, 4 exists) in the file abc.txt. The while loop is always true as there is no terminating condition. The loop is terminated in the catch block using EOFException. Eventhough, the number of objects are not known, we know pretty well that at some point EOF occurs and when occurs, the EOFException is thrown by the JVM. The EOFException is handled in catch block where while loop is exited with break statement.

The getter methods of Student class are used to retrieve the data from each Student object. The readObject() reads one object at a time and returns to st object. In each iteration, the st object stores the reference of one Student object.

If the Student is not serialized (keep in comments and try), the JVM throws "NotSerializableException".

What is transient?

transient is a keyword of Java used with variables. If a variable is declared transient, the variable is not serialized (no data persistence). That is, the variable data is not written to a file. For this, reason, see the output screen, the address (declared transient in Student class) is printed with null value.

transient variables are not serialized.

Execution: Compile all the three programs. First execute StudentWrite and then StudentRead programs. Do not execute Student as Student class does not have main() method.

Leave a Comment

Your email address will not be published.