Friday, August 13, 2010

Serialization (Store the Objects) and Deserialization (Restore the objects) in Java

Serialization:
Objects have a state and behavior.
Behavior (methods) lives Class (in memory term Stack), state (instance variable) lives with in each objects (Heap), serialization is the way to save the state of object.
If you are writing a game, you're gonna need a Save/Restore Game Feature.

Deserialization: the whole point of serializing an object is so that you can restore it back to the original state at some later date, in a different run of JVM (which might not even be the same JVM that was running at the time the object was serialized).
Deserialization is lot like serialization in reverse.


import java.io.*;
import java.lang.*;

class Model implements Serializable {//mandatory to implement serializable interface(contains not any method).
int id;

String name;

public Integer getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;

}
}

public class SampleProgram {

public static void main(String args[]) {
Model model = new Model();
model.setId(10);
model.setName("aayush");

System.out.println("the out put before serialize " + model.getId()
+ " " + model.getName() + " i am going to finish");
try {

System.out.println("Serialize start");
//create a file or use a existing file.
FileOutputStream file = new FileOutputStream("inpu.ser");
//connect the file like from source to destination
ObjectOutputStream obj = new ObjectOutputStream(file);
//writing object
obj.writeObject(model);
//closing
obj.close();

}
catch (Exception ex) {

ex.printStackTrace();

}
//declare reference value null
model = null;

try {
System.out.println("i am going to restore");
//restoring start
ObjectInputStream restore = new ObjectInputStream(
new FileInputStream("inpu.ser"));
//reading object with type cast
Model model_restore = (Model) restore.readObject();
//closing
restore.close();
//output
System.out.println(model_restore.getName());

}
catch (Exception exe) {
exe.printStackTrace();
}

}
}

No comments: