Java Serialization
Tutorial -- Learning is not just about technology, but also about dreams!
- Home
- HTML
- JavaScript
- CSS
- Vue
- React
- Python3
- Java
- C
- C++
- C#
- AI
- Go
- SQL
- Linux
- VS Code
- Bootstrap
- Git
- Local Bookmarks
Java Tutorial
Java Tutorial Java Introduction Java Development Environment Setup Java Basic Syntax Java Comments Java Objects and Classes Java Basic Data Types Java Variable Types Java Variable Naming Rules Java Modifier Types Java Operators Java Loop Structures β for, while and doβ¦while Java Conditional Statements β ifβ¦else Java switch case Statement Java Number & Math Class Java Character Class Java String Class Java StringBuffer and StringBuilder Class Java Arrays Java Date and Time Java Regular Expressions Java Methods Java Constructors Java Stream, File and IO Java Scanner Class Java Exception Handling
Java Object-Oriented
Java Inheritance Java Override/Overload Java Polymorphism Java Abstraction Java Encapsulation Java Interfaces Java Enums Java Packages Java Reflection
Java Advanced Tutorial
Java Data Structures Java Collections Framework Java ArrayList Java LinkedList Java HashSet Java HashMap Java Iterator Java Object Java NIO Files Java Generics Java Serialization Java Networking Java Sending Email Java Multithreading Java Applet Basics Java Documentation Comments Java Examples Java 8 New Features Java MySQL Connection Java 9 New Features Java Quiz Java Common Libraries
Java Serialization
Java serialization is the process of converting an object into a byte stream so that the object can be saved to a disk, transmitted over a network, or stored in memory for later deserialization, which converts the byte stream back into an object.
Serialization in Java is achieved through the java.io.Serializable interface. This interface has no methods; it is merely a marker interface used to indicate that a class can be serialized.
When you serialize an object, you wrap it into a special file that can be saved, transmitted, or stored. Deserialization is the process of opening this file, reading the serialized data, and restoring it to an object for use in the program.
Serialization is a method for saving, transmitting, and restoring objects. It allows objects to be moved and shared between different computers, which is very useful for distributed systems, data storage, and cross-platform communication.
Here are the basic concepts and usage of Java serialization:
Implementing the Serializable Interface: To make a class serializable, you need to have the class implement the java.io.Serializable interface. This tells the Java compiler that the class can be serialized. For example:
Example
import java.io.Serializable;
public class MyClass implements Serializable {
// Class members and methods
}
Serializing an Object: Use the ObjectOutputStream class to serialize an object into a byte stream. Here is a simple example:
Example
MyClass obj = new MyClass();
try {
FileOutputStream fileOut = new FileOutputStream("object.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
The above code serializes the obj object into a file named "object.ser".
Deserializing an Object: Use the ObjectInputStream class to deserialize an object from a byte stream. Here is a simple example:
Example
MyClass obj = null;
try {
FileInputStream fileIn = new FileInputStream("object.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
obj = (MyClass) in.readObject();
in.close();
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
The above code reads the byte stream from the "object.ser" file and deserializes it into a MyClass object.
The classes ObjectInputStream and ObjectOutputStream are high-level data streams that contain methods for deserializing and serializing objects.
The ObjectOutputStream class contains many write methods for writing various data types, but one method stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next object from the stream and deserializes it. Its return type is Object, so you need to cast it to the appropriate data type.
Example
To demonstrate how serialization works in Java, I will use the Employee class mentioned in previous tutorials. Assume we have defined the following Employee class, which implements the Serializable interface.
Employee.java File Code:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
Please note that for an object of a class to be successfully serialized, two conditions must be met:
- The class must implement the
java.io.Serializableinterface. - All properties of the class must be serializable. If a property is not serializable, it must be marked as transient.
If you want to know whether a standard Java class is serializable, please check the documentation for that class. Checking whether an instance of a class can be serialized is very simple; you just need to see if the class implements the java.io.Serializable interface.
Serializing an Object
The ObjectOutputStream class is used to serialize an object. The following SerializeDemo example instantiates an Employee object and serializes it to a file.
After the program executes, a file named employee.ser is created. The program produces no output, but you can understand its purpose by examining the code.
Note: When serializing an object to a file, it is standard Java convention to give the file a .ser extension.
SerializeDemo.java File Code:
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
Deserializing an Object
The following DeserializeDemo program demonstrates deserialization. The /tmp/employee.ser file stores the Employee object.
DeserializeDemo.java File Code:
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
The compilation and execution results of the above program are as follows:
Deserialized Employee...
Name: Reyan Ali
Address: Phokka Kuan, Ambehta Peer
SSN: 0
Number: 101
Here are the key points to note:
- The
try/catchblock in thereadObject()method attempts to catch theClassNotFoundException. For the JVM to deserialize an object, it must be able to find the class's bytecode. If the JVM cannot find the class during deserialization, it throws aClassNotFoundException. - Note that the return value of the
readObject()method is cast to anEmployeereference. - When the object was serialized, the value of the
SSNproperty was 111222333, but because the property is transient, that value was not sent to the output stream. Therefore, after deserialization, theSSNproperty of theEmployeeobject is 0.
5 Notes
- #0 Little Monster
193***8411@qq.com 35 Serializabl
YouTip