In my previous tutorial I have explained about writing an object to a file using the serialization concept. Once you have written to a file, that file will be transferred across the network and would reach the destination. Once it is received, the receiver has to decode that file abd reading and converting back to the original object. This process is known as Deserialization in Java. I have extend the previous example to deserialize the same object back to the original. Lets look at the example.
DeserializationExample.java
package javabeat.net.core; import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializationExample { public static void main(String args[]) { DeserializationExample deserializer = new DeserializationExample(); Employee employee = deserializer.deserialzeEmployee(); System.out.println(employee); System.out.println("Deserialization Done"); } public Employee deserialzeEmployee() { Employee employee; try { FileInputStream filein = new FileInputStream("employee.ser"); ObjectInputStream objis = new ObjectInputStream(filein); employee = (Employee) objis.readObject(); objis.close(); return employee; } catch (Exception ex) { ex.printStackTrace(); return null; } } }
Output…
Name : Krishna, ID : India Deserialization Done