We will try to understand here that what is serialization and why it is required. Example of serialization and serialization. What is difference between serialization, externalization and their respective benefit & drawbacks.
Serialization is basic feature of java. When we want to transfer an object on network using stream then we can transfer through network. We can store object with state in a file which can be used as alternative of database. We can read this file and restore object in memory and reuse it. Java also provides feature that if we want any particular variable not to serialize and all other properties of the object should get serialised can be done through transient variable. Class should implement interface java.io.serialize interface. This is an empty interface. It is JVM independent. It means that we can serialize in linux JVM particular object and deserialise in another windows JVM.
For serialization, we use ObjectOutputStream writeObject method and for deserialization, we use objectInputStream readObject method. ObjectOutputStream reads object and makes stream to save into File. File Stream is used to restore object in same state by ObjectInputStream class.
Simple Example of Serialization and Destabilization in java is given below with output :
import java.io.*; public class SerilizeDeserializeEx implements Serializable { String message; public static void main(String... args) throws Exception, IOException { File f= new File("GuruJava.txt"); SerilizeDeserializeEx sdobj= new SerilizeDeserializeEx(); //Simple Serialization example in java sdobj.message = "Best Website to learn Java i.e. Gurujava.in "; ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); out.writeObject(sdobj); //Simple DeSerialization example in java ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f)); sdobj=(SerilizeDeserializeEx)ois.readObject(); System.out.println("After deserialization message is: " +sdobj.message); } }
Output of the program :
G:\>java SerilizeDeserializeEx After deserialization message is: Best Website to learn Java i.e. Gurujava.in
Interface Externalizable extends Serializable Interface. It sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
0 comments:
Post a Comment