Persistence is the process of saving the state of an object permanently to a storage like file or database, and the state of the object can be restored at a later time. In Java terms, Persistence is nothing but Serialization. For example, the following code is used to save the state of an object in a file.
Assuming that there is some class called Flower implementing java.io.Serializable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class Flower implements Serializable {
private String name;
private String colour;
public Flower(){
}
public Flower(String name, String colour){
this.name = name;
this.colour = colour;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "The " + name + " is " + colour + " in colour.";
}
} |
The following code shows how to persist an object of the class Flower.
1 2 3 4 | ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("flower"));
output.writeObject(new Flower("Orchid","Purple"));
output.close(); |
If we want to re-construct the original object from the file "flower", then the following piece of code will help.
1 2 3 4 | ObjectInputStream input = new ObjectInputStream(
new FileInputStream("flower"));
Flower orchid = (Flower)input.readObject();
System.out.println(orchid); |
If we try to open the file "flower", nothing can be understood from that, since the format of file is binary.
The output of reconstructing the object from file is,
1 | The Orchid is Purple in colour. |
We have just seen a simple example of persisting an object. Let us now get into our topic of interest , i.e Persisting Object State in Xml Format. The following program shows how to save and restore the state of an object in an appropriate way by using Xml format.
1 2 3 4 5 | FileOutputStream fileOutputStream = new FileOutputStream("flower.xml");
XMLEncoder encoder = new XMLEncoder(fileOutputStream);
Flower orchid = new Flower("Rose","Red");
encoder.writeObject(orchid);
encoder.close(); |
The above code makes use of java.beans.XMLEncoder to save the object state in Xml Format. Given below is the code to read the xml file content for re-constructing the object.
1 2 3 | XMLDecoder decoder = new XMLDecoder(new FileInputStream("flower.xml"));
Flower flower = (Flower)decoder.readObject();
System.out.println(flower); |
The output of reconstructing the object from the flower.xml file is,
1 | The Rose is Red in colour. |






September 25, 2007
Java