What is the serialization and deserialization of Java? Why do I need serialization and deserialization? How do I implement the serialization and deserialization of Java? This paper focuses on these problems.
1.Java 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.
2. Why serialization and deserialization are required
We know that when two processes communicate remotely, they can send each other various types of data, including text, pictures, audio, video, etc., which are transmitted over the network in the form of a binary sequence. So when two Java processes are communicating, can we implement the inter-process object transfer? The answer is yes. How do we do that? This requires the serialization and deserialization of Java. In other words, on the one hand, the sender needs to convert the Java object to a sequence of bytes and then transfer it over the network, on the other hand, the receiver needs to recover the Java object from the sequence of bytes.
After we have clarified why Java serialization and deserialization are needed, we naturally think of the benefits of Java serialization. The advantage of this is the persistence of data, through serialization can be permanently saved to the hard disk (usually stored in the file), the second, the use of serialization to achieve remote communication, that is, the transmission of the object's byte sequence on the network.
3. How to implement the serialization and deserialization of Java
1) Serialization API in JDK class library
Java.io.ObjectOutputStream: Represents an 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.
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.
2) Requirements for serialization
Only an object of a class that implements the serializable or Externalizable interface can be serialized, otherwise an exception is thrown.
3) Methods of implementing the serialization and deserialization of Java objects
Assuming a student class, its objects need to be serialized, there are three ways to do it:
Method One: If the student class implements only the serializable interface , it can be serialized and deserialized in the following way
ObjectOutputStream uses the default serialization method to serialize non-transient instance variables of the student object.
Objcetinputstream uses the default deserialization method to deserialize non-transient instance variables of the student object.
Method Two: If the student class only implements the Serializable interface, and also defines ReadObject (ObjectInputStream in) and WriteObject (Objectoutputsteam out), Serialization and deserialization are performed in the following manner.
ObjectOutputStream calls the Student object's WriteObject (ObjectOutputStream out) method to serialize.
ObjectInputStream invokes the Student object's ReadObject (ObjectInputStream in) method for deserialization.
Method Three: If the student class implements the Externalnalizable interface , and the student class must implement Readexternal (ObjectInput in) and Writeexternal ( ObjectOutput out) method, the serialization and deserialization are performed in the following manner.
ObjectOutputStream invokes the Student object's writeexternal (ObjectOutput Out) method for serialization.
ObjectInputStream invokes the Student object's readexternal (ObjectInput in) method for deserialization.
4) steps to serialize in the JDK class library
Step One: 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"));
Step two: Write the object through the WriteObject () method of the object output stream:
Out.writeobject ("Hello");
Out.writeobject (New Date ());
5) steps to deserialize in the JDK class library
Step One: 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"));
Step Two: 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 the deserialization, it is necessary to ensure that the output stream writes objects to the object in the same order as the objects are read from the object input stream.
In order to better understand the Java serialization and deserialization, select the method one encoding implementation.
The student class is defined as follows:
[Java]View PlainCopy
- Package Com.jieke.io;
- Import java.io.Serializable;
- /**
- *title: Student Class
- *description: Student class that implements the serialization interface
- *copyright:copyright (c) 2012
- *filename:student.java
- * @author Wang luqing
- * @version 1.0
- */
- Public class Student implements Serializable
- {
- private String name;
- private char sex;
- private int year;
- private double GPA;
- Public Student ()
- {
- }
- Public Student (String name,char-sex,int year,double GPA)
- {
- this.name = name;
- this.sex = sex;
- this.year = year;
- This.gpa = GPA;
- }
- public void SetName (String name)
- {
- this.name = name;
- }
- public void Setsex (char sex)
- {
- this.sex = sex;
- }
- public void setyear (int year)
- {
- this.year = year;
- }
- public void Setgpa (double gpa)
- {
- This.gpa = GPA;
- }
- Public String getName ()
- {
- return this.name;
- }
- public Char getsex ()
- {
- return This.sex;
- }
- public int getYear ()
- {
- return this.year;
- }
- public Double Getgpa ()
- {
- return This.gpa;
- }
- }
Serializes the object of the student class to the file O:\\java\\com\\jieke\\io\\student.txt and deserializes it from the file, displaying the result to the console. The code is as follows:
[Java]View PlainCopy
- Import java.io.*;
- /**
- *title: Apply Student class
- *description: Realizing the serialization and deserialization of student class instances
- *copyright:copyright (c) 2012
- *filename:usestudent.java
- * @author Wang luqing
- * @version 1.0
- */
- Public class Usestudent
- {
- public static void Main (string[] args)
- {
- Student st = New Student ("Tom",' M ',3.6);
- File File = new file ("O:\\java\\com\\jieke\\io\\student.txt");
- Try
- {
- File.createnewfile ();
- }
- catch (IOException e)
- {
- E.printstacktrace ();
- }
- Try
- {
- //student Object Serialization Process
- FileOutputStream fos = new FileOutputStream (file);
- ObjectOutputStream Oos = new ObjectOutputStream (FOS);
- Oos.writeobject (ST);
- Oos.flush ();
- Oos.close ();
- Fos.close ();
- //student Object Deserialization process
- FileInputStream FIS = new FileInputStream (file);
- ObjectInputStream ois = new ObjectInputStream (FIS);
- Student st1 = (Student) ois.readobject ();
- System.out.println ("name =" + St1.getname ());
- System.out.println ("sex =" + st1.getsex ());
- SYSTEM.OUT.PRINTLN ("year =" + St1.getyear ());
- SYSTEM.OUT.PRINTLN ("GPA =" + St1.getgpa ());
- Ois.close ();
- Fis.close ();
- }
- catch (classnotfoundexception e)
- {
- E.printstacktrace ();
- }
- catch (IOException e)
- {
- E.printstacktrace ();
- }
- }
- }
The results are as follows:
Name = Tom
Sex = M
Year = 20
GPA = 3.6
Summarize:
1) Java serialization is the conversion of an object into a sequence of bytes, while the Java deserialization is the restoration of a sequence of bytes to a Java object.
2) The use of Java serialization and deserialization technology, one can achieve the persistence of data, in the MVC pattern is very useful, and the other is the object data can be remote communication.
Translated from: http://blog.csdn.net/wangloveall/article/details/7992448/
The original author is Wang Lu sentiment. Please respect the copyright of the original author
Serialization and deserialization of Java