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.
also read:
Assuming that there is some class called Flower
implementing java.io.Serializable
.
[code lang=”java”]
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.";
}
}
[/code]
The following code shows how to persist an object of the class Flower
.
[code lang=”java”]
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("flower"));
output.writeObject(new Flower("Orchid","Purple"));
output.close();
[/code]
If we want to re-construct the original object from the file "flower"
, then the following piece of code will help.
[code lang=”java”]
ObjectInputStream input = new ObjectInputStream(
new FileInputStream("flower"));
Flower orchid = (Flower)input.readObject();
System.out.println(orchid);
[/code]
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,
[code lang=”java”]
The Orchid is Purple in colour.
[/code]
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.
[code lang=”java”]
FileOutputStream fileOutputStream = new FileOutputStream("flower.xml");
XMLEncoder encoder = new XMLEncoder(fileOutputStream);
Flower orchid = new Flower("Rose","Red");
encoder.writeObject(orchid);
encoder.close();
[/code]
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.
[code lang=”java”]
XMLDecoder decoder = new XMLDecoder(new FileInputStream("flower.xml"));
Flower flower = (Flower)decoder.readObject();
System.out.println(flower);
[/code]
The output of reconstructing the object from the flower.xml
file is,
[code lang=”java”]
The Rose is Red in colour.
[/code]
Leave a Reply