Serialization and Deserialization
File handling in Java allows you to perform various operations on files, including serialization and deserialization. Serialization is the process of converting objects into a byte stream, while deserialization is the process of reconstructing objects from a byte stream. This can be particularly useful when you want to store Java objects persistently or send them across a network.
1. Serialization:
Serialization Example:
In this example, a Student
object is serialized and saved into a file named "student.ser". The ObjectOutputStream
class is used to write the object to the file. The Student
class implements Serializable
.
2. Deserialization:
Deserialization Example:
In this example, the Student
object is deserialized from the "student.ser" file using the ObjectInputStream
class. The object is cast back to the Student
class, and its display()
method is called.
Explanation:
Serialization:
ObjectOutputStream
is used to serialize objects. It writes primitive data types and graphs of Java objects to anOutputStream
.The class to be serialized (
Student
in this case) implements theSerializable
interface, which is a marker interface indicating the class is serializable.Serialized objects can be saved to a file for future use or transmitted over a network.
Deserialization:
ObjectInputStream
is used for deserialization. It reads objects from anInputStream
and deserializes them.The class being deserialized must have the same serialVersionUID as the class that was serialized.
The deserialized object can be cast back to its original class for further use.
Remember to handle IOException
and ClassNotFoundException
to ensure your file handling, serialization, and deserialization operations are error-free and robust.
Last updated