Object Serialization

A serialized object is an object represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Classes that must be serializable implements interface Serializable. Interface Serializable is a tagging interface. Such an interface contains no methods. A class that implements Serializable is tagged as being a Serializable object. This is important because an ObjectOutputStream will not output an object unless it is a Serializable object, which is the case for any object of a class that implements Serializable.

In a class that implements Serializable, the programmer must ensure that every instance variable of the class is a Serializable type. By default, all primitive-type variables are serializable.

In the following simple example AccountSerializable represents a bank account. The objects can be serializable because this class extends Serializable interface.

  • AccountSerializable.java
import java.io.Serializable;
 
public class AccountSerializable implements Serializable
{
    private int account;
    private String name;
    private double balance;
 
    public AccountSerializable()
    {
        this(0,"",0);
    }
 
    public AccountSerializable(int account, String name, double balance)
    {
        setAccount(account);
        setName(name);
        setBalance(balance);
    }
 
    public int getAccount()
    {
        return account;
    }
 
    public void setAccount(int account)
    {
        this.account = account;
    }
 
    public double getBalance()
    {
        return balance;
    }
 
    public void setBalance(double balance)
    {
        this.balance = balance;
    }
 
    public String getName()
    {
        return name;
    }
 
    public void setName(String name)
    {
        this.name = name;
    }
 
    @Override
    public String toString()
    {
        return " Account: " + getAccount() + " Name: " + getName() + " Balance: " + getBalance();
    }
 
}
  • CreateSequentialFile.java : This class creates two objects of type AccountSerializable and stores them inside a file. Run this first.
import java.io.*;
import java.util.*;
 
public class CreateSequentialFile
{
    private ObjectOutputStream output; // output data to a file
 
    // allow user to specify file name
    public void openFile()
    {
        try
        // open file
        {
            //wrap FileOutStream in an ObjectOutpuStream
            output = new ObjectOutputStream(new FileOutputStream("clients.ser"));
        } // end try
        catch (IOException ioException)
        {
            System.err.println("Error opening file.");
        } // end catch
    } // end method openFile
 
    public void AddRecords()
    {
        // the records can come from the console or from a gui here
        AccountSerializable record1 = new AccountSerializable(1,"Chrys",100);
        AccountSerializable record2 = new AccountSerializable(2,"Maro",200);
        try
        {
            output.writeObject( record1 );
            output.writeObject( record2 ); // output record 
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // output record
 
    }
 
    public void closeFile()
    {
        try
        {
            if(output != null)
                output.close();
 
        } catch (Exception e)
        {
            // TODO: handle exception
        }
    }
 
    public static void main(String[] args)
    {
        CreateSequentialFile cf = new CreateSequentialFile();
        cf.openFile();
        cf.AddRecords();
        cf.closeFile();
    }
 
}
  • ReadSequentialFile.java : This class reads the saved file and prints the accounts. Run this last.
import java.io.*;
 
public class ReadSequentialFile
{
    private ObjectInputStream input;
 
    public void openFile()
    {
        try
        // open file
        {
            // wrap FileOutStream in an ObjectOutpuStream
            input = new ObjectInputStream(
                    new FileInputStream("clients.ser"));
        } // end try
        catch (IOException ioException)
        {
            System.err.println("Error opening file.");
        }
    }
 
    public void readRecords()
    {
        AccountSerializable record;
 
        try
        {
            while (true)
            {
                record = (AccountSerializable) input.readObject();
                // display contents
                System.out.println(record.toString());
            }
        } catch (EOFException endOfFileException)
        {
            return;
        } catch (ClassNotFoundException classNotFoundException)
        {
            System.err.println("Unable to create object.");
        } // end catch
        catch (IOException ioException)
        {
            System.err.println("Error during read from file.");
        } // end catch
 
    }
 
    public void closeFile()
    {
        try
        {
            if (input != null)
                input.close();
 
        } catch (Exception e)
        {
            // TODO: handle exception
        }
    }
 
    public static void main(String[] args)
    {
        ReadSequentialFile application = new ReadSequentialFile();
 
        application.openFile();
        application.readRecords();
        application.closeFile();
 
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.