Serializing and Deserializing Objects
The serialization mechanism in Java provides the means for persisting objects beyond a single run of a Java program. To serialize an object, make sure that the declaring class implements the java.io.Serializable interface. Then obtain an ObjectOutputStream to write the object to and call the writeObject() method on the ObjectOutputStream. To deserialize an object, obtain an ObjectInputStream to read the object from and call the readObject() method on the ObjectInputStream. The following code excerpts illustrate how an object is stored in the file by Serialize and getting object from file by Deserialize.
private static String fileName = "./objectholder.ser";
public static void serializeObject(Object obj) {
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(fileName));
out.writeObject(obj);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object deSerializeObject(){
try {
Object obj = null;
File file = new File(fileName);
if(file.exists()) {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
obj = in.readObject();
in.close();
}
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
how to call these methods?
//serialize the object
MyObject fileObjs = new MyObject();
serializeObject(fileObjs);
// Deserialize the object
MyObject fileObjs = (MyObject)deSerializeObject();
Where MyObject is class with implements of Serializable interface.
Serialize the object myObject of type MyObject. The file output stream is created for the file named myObject.ser. The object is actually persisted in this file on ,and read the object back from the file objectholder.ser. If you list the files in the directory where this code's .class file is stored, you will see a new file called objectholder.ser added to the listing.
Let us share our views in java. Not only java, we can also share examples and configurations on Spring, Hibernate, javascript, CSS and Sqlserver queries. This blog will help you in giving the complete information and resolving your complete java related problems like the problems in core java, servlets, jsp spring, hibernate. And also the web technologies which includes all css related problems(Web 2.0).and java script and the latest smart jquery java script frame work
Showing posts with label How to Serializing and Deserializing Objects. Show all posts
Showing posts with label How to Serializing and Deserializing Objects. Show all posts
Aug 1, 2009
Subscribe to:
Posts (Atom)