Serialization in java

Serialization in java

Serialization is the process of storing object contents into a file. The class whose objects are stored in the file should implement ‘Serializable’ of java.io package.

To store the class objects into a file, follow these steps:

First, attach objectfile to FileOutputStream. This helps to write data into objfile.

FileOutputStream fos = new¬†FileOutputStream(“objfile”);

Then attach FileOutputStream to ObjectOutputStream

ObjectOutputStream oos = new ObjectOutputStream(fos);

Now, ObjectOutputStream can write objects using writeObject() method to FileOutputStream, which store them into objfile. Storing object like this is called serialization, where objects can be retrieved back from a file is called de-serialization.

To create employee class whose objects are to be stored into a file.
import java.io.Serializable;
public class employee implements Serializable
{
int id;
String name;
public employee(int id, String name)
{
this.id = id;
this.name = name;
}
}
To show serialization of objects.
import java.io.*;
class test
{
public static void main(String args[])throws Exception
{
employee e =new employee(1,”Adam”);
FileOutputStream fos=new FileOutputStream(“objfile”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(e);
oos.flush();
System.out.println(“success”);
}
}
de-serialization
import java.io.*;
class Detest
{
public static void main(String args[])throws Exception
{
ObjectInputStream in=new ObjectInputStream(new FileInputStream(“objfile”));
employee e=(employee)in.readObject();
System.out.println(e.id+” “+e.name);
in.close();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *