What is Java serialization and deserialization? Why serialization and deserialization? How to Implement Java serialization and deserialization? This article discusses these issues.
1. Java serialization and deserialization
Java serialization refers to the process of converting a Java object into a byte sequence, while Java deserialization refers to the process of restoring a byte sequence to a Java object.
2. Why serialization and deserialization?
We know that when two processes communicate remotely, they can send various types of data to each other, including text, images, audio, and video, the data is transmitted over the network in the form of binary sequences. So when two Java processes communicate, can we implement object transfer between processes? The answer is yes. How can this problem be achieved? This requires Java serialization and deserialization. In other words, on the one hand, the sender needs to convert the Java object into a byte sequence and then transfer it over the network; on the other hand, the receiver needs to restore the Java object from the byte sequence.
After clarifying why Java serialization and deserialization are required, we naturally think about the benefits of Java serialization. The advantage is that data persistence can be realized, and data can be permanently stored on the hard disk (usually stored in files) through serialization. The second is that the serialization can be used for remote communication, that is, the byte sequence of objects transmitted over the network.
3. How to Implement Java serialization and deserialization
1) serialize the API in the JDK class library
Java. io. ObjectOutputStream: indicates the object output stream.
Its writeObject (Object obj) method can serialize the obj Object specified by the parameter and write the obtained byte sequence to a target output stream.
Java. io. ObjectInputStream: indicates the object input stream.
Its readObject () method reads byte sequences from the source input stream, deserializes them into an object, and returns it.
2) Requirements for serialization
Only the objects of classes that implement the Serializable or Externalizable interface can be serialized. Otherwise, an exception is thrown.
3) Java object serialization and deserialization Methods
Assume that the object of a Student class needs to be serialized. There are three methods:
Method 1: If the Student class only implements the Serializable interface, serialization and deserialization can be performed as follows:
ObjectOutputStream uses the default serialization method to serialize non-transient instance variables of the Student object.
ObjcetInputStream adopts the default deserialization method to deserialize non-transient instance variables of the Student object.
Method 2: If the Student class only implements the Serializable interface and also defines readObject (ObjectInputStream in) and writeObject (ObjectOutputSteam out), the following methods are used for serialization and deserialization.
ObjectOutputStream calls the writeObject (ObjectOutputStream out) method of the Student object for serialization.
ObjectInputStream calls the readObject (ObjectInputStream in) method of the Student object for deserialization.
Method 3: if the Student class implements the Externalnalizable interface and the Student class must implement the readExternal (ObjectInput in) and writeExternal (ObjectOutput out) methods, serialization and deserialization are performed as follows.
ObjectOutputStream calls the writeExternal (ObjectOutput out) method of the Student object for serialization.
ObjectInputStream calls the readExternal (ObjectInput in) method of the Student object for deserialization.
4) JDK class library serialization steps
Step 1: Create an object output stream that can wrap a target output stream of another type, such as a file output stream:
ObjectOutputStream out = new ObjectOutputStream (new fileOutputStream ("D: \ objectfile. obj "));
Step 2: Write an object using the writeObject () method of the object output stream:
Out. writeObject ("Hello ");
Out. writeObject (new Date ());
5) deserialization steps in the JDK class library
Step 1: Create an object input stream, which can wrap an input stream of another type, such as a file input stream:
ObjectInputStream in = new ObjectInputStream (new fileInputStream ("D: \ objectfile. obj "));
Step 2: Read the object using the readObject () method of the object output stream:
String obj1 = (String) in. readObject ();
Date obj2 = (Date) in. readObject ();
Note: to read data correctly and complete deserialization, the write Object Sequence of the output stream to the object must be consistent with that of the read object in the input stream.
To better understand Java serialization and deserialization, select method 1 encoding implementation.
The Student class is defined as follows:
[Java]
Package com. jieke. io;
Import java. io. Serializable;
/**
* Title: Student
* 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;
}
}
Serialize the Student Class Object to the file O: \ Java \ com \ jieke \ io \ student.txt, and deserialize the object to display the result to the console. The Code is as follows:
[Java]
Import java. io .*;
/**
* Title: applied to students
* Description: serializes and deserializes student instances.
* Copyright: copyright (c) 2012
* Filename: UseStudent. java
* @ Author Wang Luqing
* @ Version 1.0
* // Www.heatpress123.net
Public class UseStudent
{
Public static void main (String [] args)
{
Student st = new Student ("Tom", 'M's, 20, 3.6 );
File file = new File ("O: \ Java \ com \ jieke \ io \ student.txt ");
Try
{
File. createNewFile ();
}
Catch (IOException e)
{
E. printStackTrace ();
}
Try
{
// Serialization process of Student object
FileOutputStream fos = new FileOutputStream (file );
ObjectOutputStream oos = new ObjectOutputStream (fos );
Oos. writeObject (st );
Oos. flush ();
Oos. close ();
Fos. close ();
// Deserialization process of Student object
FileInputStream FCM = new FileInputStream (file );
ObjectInputStream ois = new ObjectInputStream (FCM );
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 ();
FCM. close ();
}
Catch (ClassNotFoundException e)
{
E. printStackTrace ();
}
Catch (IOException e)
{
E. printStackTrace ();
}
}
}
The result is as follows:
Name = Tom
Sex = M
Year = 20
Gpa = 1, 3.6
Summary:
1) Java serialization converts an object to a byte sequence, while Java deserialization restores the byte sequence to a Java object.
2) Java serialization and deserialization technologies are used. First, data persistence can be realized, which is useful in the MVC mode. Second, remote communication can be performed on object data.