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
.
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
.
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.
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,
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.
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.
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,
The Rose is Red in colour.