This article mainly discusses the serialization and deserialization of Java objects, OK, the direct entry question:
I. Meaning of serialization and deserialization:
Java serialization refers to the process of converting a Java object to a sequence of bytes, while Java deserialization refers to the process of reverting a sequence of bytes to a Java object.
Two. Serialization and deserialization purposes:
Convert Java objects into binary bytes to communicate or transfer in two processes, improve communication efficiency and achieve data persistence
Three. Serialization-related classes in the JDK:
1. Java.io.ObjectOutputStream: Indicates the object output stream
Its writeobject (Object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.
2.java.io.objectinputstream: Represents an object input stream
Its readobject () method reads the sequence of bytes from the source input stream, deserializes them into an object, and returns them.
Only objects of a class that implement the serializable or Externalizable interface can be serialized, otherwise an exception is thrown
Four. Steps to serialize in the JDK class library :
1. Create an object output stream that can wrap a different type of target output stream, such as a file output stream:
ObjectOutputStream out = new ObjectOutputStream (New FileOutputStream ("D:\\objectfile.obj"));
2. Write an object by using the WriteObject () method of the object output stream:
out.writeobject ("Hello");
Out.writeobject (New Date ());
Five. Steps to deserialize in the JDK class library
1. Create an object input stream that can wrap a different type of input stream, such as a file input stream:
ObjectInputStream in = new ObjectInputStream (New FileInputStream ("D:\\objectfile.obj"));
2. Read the object through the ReadObject () method of the object output stream:
String obj1 = (string) in.readobject ();
Date Obj2 = (date) in.readobject ();
Note: In order to correctly read the data and complete deserialization, you must ensure that the output stream to the object is written in the same order as the object is read from the object input stream.
Reference article:
Http://www.cnblogs.com/xdp-gacl/p/3777987.html
Http://www.cnblogs.com/xudong-bupt/archive/2013/05/19/3086493.html
Http://www.2cto.com/kf/201405/305380.html
Serialization and deserialization of Java objects