Thursday, September 18, 2014

Java serialization de-serialization

In previous post we seen the example of interface in Java. In this Java serialization de-serialization with example.
Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
Create a Java project called “varemads.java.serilization”. Create the following Java object called Employee
import java.io.Serializable;
public class Employee implements Serializable {
private String firstName;
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return “Employee [firstName=" + firstName + ", lastName=" + lastName+ "]“;
}
}
The following code example show you how you can serializable and de-serializable this object.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
public static void main(String[] args) {
String filename = “varemads.ser”;
Employee employee = new Employee(“Arvind”, “Kanjariya”);

// save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(employee);

out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// read the object from file
// save the object to file
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (Person) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(employee);
}
}
Note:The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject()method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can’t find a class during the deserialization of an object, it throws a ClassNotFoundException. 

No comments:

Post a Comment