Log in
updated 11:29 AM UTC, May 4, 2016

Serialization in Java explained with an example program

  • Written by Madhu V Rao
  • Published in Core Java

Here is a shared java project to explain the Serialization/De-serialization.

Just do a git clone of the project using the command below:

 git clone https://github.com/mail2madhva/SerializeExample.git

It has three main classes : MainClass.java is the class which tests the serialization and de-serialization.

Other two classes are the Objects which implement the Serializable interface, so these objects gets serialized.

The serialized data gets stored in the data.bin file on the file system.

The project shows how to serialize an array as well. PersonList stores the list of the Persons in an array list.

 This part of the code in the MainClass.java does the serialization:

String filename = "data.bin";
try {
	ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
	os.writeObject(list);
	os.close();
} catch (FileNotFoundException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

 The above program is self explanatory , The writeObject() method of ObjectOutputStream is used to serialize the object and which is written to a file using FileOutputStream.

This part of the code does the de-serialization, i.e reads the objects from the file.

try {
	ObjectInputStream is = new ObjectInputStream(new FileInputStream(filename));
        PersonList listRead = (PersonList) is.readObject();
			
	Iterator<Person> it = listRead.getPersonList().iterator();
	
	Person readPerson = null;
	while(it.hasNext()) {
	        readPerson = it.next();
				
		System.out.println("Person  name = " + readPerson.getName() + " age = " + readPerson.getAge() + " email = " + readPerson.getEmail());
				
	}
			
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (ClassNotFoundException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

FileInputStream is used to read the file. ObjectInputStream is created for that file stream. "is.readObject()" reads the Objects from the FileInputStream.

 


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest