Wednesday 7 October 2015

Serializable in Java

java.io.Serializable
Since JDK 1.1 : Marker interface

Java Serialization API allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage.

Deserialization is the process of converting Object stream to actual Java Object to be used in our program.

transient keyword can use to avoid the Serialization of object property in stream.
static variable values cannot serialized as they belong to class and not object.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/** A simple class with generic serialize and deserialize method implementations*/
public class SerializationUtil {

       // deserialize to Object from given file
       public static Object deserialize(String fileName)
                     throws IOException, ClassNotFoundException {
              FileInputStream fis = new FileInputStream(fileName);
              ObjectInputStream ois = new ObjectInputStream(fis);
              Object obj = ois.readObject();
              ois.close();
              return obj;
       }

       // serialize the given object and save it to file
       public static void serialize(Object obj, String fileName) throws IOException {
              FileOutputStream fos = new FileOutputStream(fileName);
              ObjectOutputStream oos = new ObjectOutputStream(fos);
              oos.writeObject(obj);
              fos.close();
       }
}


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...