Serialization | Deserialization |
ObjectOutputStream class is used to serialize an object to a byte stream. | ObjectInputStream class is used to deserialize a byte stream into an object |
Commonly used for saving object states persistently, transmitting objects over a network, or sharing data between different applications. | Crucial for scenarios where data, previously serialized, needs to be retrieved and used in its original object form. Common use cases include reading objects from files, receiving serialized data over a network, or reconstructing objects stored in databases. |
Object to Byte Stream Example
// Serialize an object to a byte stream
ByteArrayOutputStream bytArrOPStream = new ByteArrayOutputStream();
ObjectOutputStream objOPStream = new bjectOutputStream(bytArrOPStream);
// Example object to be serialized
MyObject myObject = new MyObject();
// Serialize the object
objOPStream.writeObject(myObject);
// Get the byte stream
byte[] byteStream = bytArrOPStream.toByteArray();
// Close streams
objOPStream.close();
bytArrOPStream.close();
Byte Stream to Object Example
// Deserialize an object from a byte stream
ByteArrayInputStream bytArrIPStream = new ByteArrayInputStream(byteStream);
ObjectInputStream objIPStream = new ObjectInputStream(bytArrIPStream);
// Deserialize the object
MyObject deserializedObject = (MyObject) objIPStream.readObject();
// Close streams
objectInputStream.close();
bytArrIPStream.close();
Comments