Archive for the ‘Core Java’ Category

Object Serialization:-

Serialization is a process of storing the object instance to a disk file. Serialization stores state of the object i.e. member variable values to disk.
Deserialization is reverse of serialization i.e. it’s a process of reading objects from a file where they have been stored.

Object serialization is the process of saving an object’s state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. The
Java Serialization API provides a standard mechanism for developers to handle object serialization.
The API is small and easy to use, provided the classes and methods are understood.

This mechanism has been added into the Java language for mainly two reasons:

  • the JavaBeans mechanism makes heavy use of serialization
  • remote method invocation (RMI) allows us to automatically use objects located at another host in the network just like any local objects.

How ?

package lib;

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

public class ObjectSerialization {

public static void main(String[] args) {

try {

//Create a file to write the serialized tree to.
FileOutputStream ostream = new FileOutputStream(“tree.txt”);
//Create the output stream
ObjectOutputStream p = new ObjectOutputStream(ostream);

//Object ceations with serializable
Tree tree = new Tree();

//Create a tree with three levels.
//Write the tree to the stream.

//close the file.

//Open the file and set to read objects from it.
FileInputStream istream = new FileInputStream(“tree.txt”);
ObjectInputStream q = new ObjectInputStream(istream);

// Read a tree object, and all the subtrees */
Tree new_tree = (Tree)q.readObject();

System.out.println(” *** “+new_tree.getName());
} catch (Exception ex) {

Thanks & Regards,
Rajeshkumar. E |


Read Full Post »