Example of readObject and writeObject in Serialization in Java
December 09, 2012
Java classes which requires user defined handling of serialization and deserialization, then readObject and writeObject is used. Before looking into the example, we need to know about transient variable. . Transient variable or object is not serialized. We will serialize and then deserialize object. writeObject method writes the byte stream in physical location. To use the default mechanism to save the state of object, use defaultWriteObject. readObject method is used to read byte stream from physical location and type cast to required class. To read the data by default mechanism we use defaultReadObject .
In default mechanism static field and transient variable are not serialized or deserialized. As an example if we want to serialize transient variable we need to use readObject and writeObject. Find the example.
ConcretePage.java
package com.concretepage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class ConcretePage implements Serializable { public static final long serialVersionUID = 1L; private String user; private transient String author; public ConcretePage(String user,String author){ this.user=user; this.author=author; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(this.author); } private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException { in.defaultReadObject(); this.author = (String)in.readObject(); } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
package com.concretepage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ConcreteMain { public static void main(String... args) throws Exception, IOException{ File f= new File("a.txt"); ConcretePage cp= new ConcretePage("Ankita","Atul"); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); out.writeObject(cp); ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)); cp=(ConcretePage)in.readObject(); System.out.println("After deserialize user is: " +cp.getUser()+" and author is:"+cp.getAuthor()); } }