Java Object Serialization with examples of File and ServerSocket

Java object Serialization was first introduced in JDK 1.1, it serves as mechanism to write Java objects as an array of bytes into a file so it can be transported between application to application, disk to disk, etc. For example, application A uses ObjectOutputStream to write a Java object as an array of bytes into a stream which will can be delivered to applicaton B, and application B uses ObjectInputStream to read the file and deserializes it, thus getting back the original Java object.

All the work that does the serialization and deserialization is by ObjectOutputStream and ObjectInputStream

To serialize an object, the object has to implment Serializable. For exammple, Student.java

import java.io.Serializable;
public class Student implements java.io.Serializable
{
   private int id;
   private String name;

   public Student(int id, String name)
   {
	   this.id=id;
	   this.name=name;
   }
   public String toString()
   {
	return "Student ID: "+id+"\nStudent Name: "+name;
	   
   }
}

This SerializeToFile.java demonstrates serializing an ArrayList of Students to a file and deserializing it from the file.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class SerializeToFile {

	public static void serializeStudents(ArrayList<Student> students, String file)
	{
		FileOutputStream fileOut;
		try
		 {
		    fileOut = new FileOutputStream(file);
		    ObjectOutputStream out = new ObjectOutputStream(fileOut);
		    out.writeObject(students);
		    out.close();
		    fileOut.close();
		 }catch(Exception e)
		 {
		     e.printStackTrace();
		     return;
		 }  
		return;
	}
	
	public static ArrayList<Student> deserializeStudents(String file)
	{
		ArrayList<Student> students = null;
	      try
	      {
	         FileInputStream fileIn = new FileInputStream(file);
	         ObjectInputStream in = new ObjectInputStream(fileIn);
	         students = (ArrayList<Student>) in.readObject();
	         in.close();
	         fileIn.close();
	     }catch(Exception e)
	     {
	         e.printStackTrace();   
	         return null;
	     }
	     return students;
	}
	
	public static void main(String args[])
	{
		ArrayList<Student> students = new ArrayList<Student>();
		Student s1 = new Student(1254783,"Amy");
		Student s2 = new Student(1525486,"Ben");
		students.add(s1);
		students.add(s2);
		
		String file="student.ser";
	    serializeStudents(students, file);
	    ArrayList<Student> receivedStudents = deserializeStudents(file);
	    
        for(int i=0; i<receivedStudents.size(); i++)
        {
       	 System.out.println(receivedStudents.get(i).toString());
        }
	}
}

The StudentServer.java and StudentClient.java below demonstrates exchanging the serialized ArrayList of students between a server and client through ServerSocket.
First, run the StudentServer.java and then run the StudentClient.java to get a list of students.

import java.net.*;
import java.util.ArrayList;
import java.io.*;

public class StudentServer extends Thread
{
   private ServerSocket serverSocket;
	
   public StudentServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(20000);//20 seconds
   }

   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("Server: Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Server: Just connected to " + server.getRemoteSocketAddress());
            
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println("Server gets the message from client: "+in.readUTF());
            
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Sure, here is the object.");
            
            ObjectOutputStream objectOut = new ObjectOutputStream(server.getOutputStream());
            ArrayList<Student> students = new ArrayList<Student>();
     	    Student s1 = new Student(33333333,"Carl");
    	    Student s2 = new Student(44444444,"Denny");
    	    students.add(s1);
    	    students.add(s2);
            objectOut.writeObject(students);
            
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Server: Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt("6066");
      try
      {
         Thread t = new StudentServer(port);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}
import java.net.*;
import java.util.ArrayList;
import java.io.*;

public class StudentClient
{
   public static void main(String [] args)
   {
      String serverName = "localhost";
      int port = Integer.parseInt("6066");
      try
      {
         System.out.println("Client: Connecting to " + serverName + " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Client: Just connected to " + client.getRemoteSocketAddress());
         
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
         out.writeUTF("Hello Server, can you give me a list of students?" + client.getLocalSocketAddress());
         
         
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("Client gets the message from the server: "+in.readUTF());
         
         ObjectInputStream objectIn = new ObjectInputStream(inFromServer);
         ArrayList<Student> students = (ArrayList<Student>) objectIn.readObject();
         for(int i=0; i<students.size(); i++)
         {
        	 System.out.println(students.get(i).toString());
         }
         
         client.close();
         
      }catch(Exception e)
      {
         e.printStackTrace();
         System.out.println(e);
      }
   }
}

Note: Performance wise, Java Object Serialization is slow for small number of objects compared to using xml or json, but it is faster than using xml or jason for large number of objects. Thus for applications that make request for a small number of objects, it is better to use xml or jason, for applications that make request for a large number of objects, it is better to use Java Object serialization.

Besides the standard Java Object Serialization and using xml or json for data transmission, there is an open source Java serialization framework called Kryo, which can be downloaded from google code. The goals of Kryo are speed, efficiency, and an easy to use API.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search