Java Serialization is the process of converting an object’s state to a stream of bytes in order to store it or transmit it to another location.
Deserialization is the reverse process of converting the stream of bytes back into an object.
Here’s an example of Java serialization and deserialization with a Car
class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.Serializable; class Car implements Serializable { private String model; private int year; public Car(String model, int year) { this.model = model; this.year = year; } public String toString() { return model + " " + year; } } public static void main(String[] args) { Car car = new Car("Sedan", 2020); try { FileOutputStream fos = new FileOutputStream("car.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(car); oos.close(); fos.close(); System.out.println("Serialized car: " + car); } catch (Exception e) { e.printStackTrace(); } Car deserializedCar; try { FileInputStream fis = new FileInputStream("car.ser"); ObjectInputStream ois = new ObjectInputStream(fis); deserializedCar = (Car) ois.readObject(); ois.close(); fis.close(); System.out.println("Deserialized car: " + deserializedCar); } catch (Exception e) { e.printStackTrace(); } } |
In this example, we have a Car
class that implements the Serializable
interface.
This interface is used to indicate that a class is serializable. To serialize an instance of the Car
class, we first create a FileOutputStream
and an ObjectOutputStream
and write the object to the stream using the writeObject
method.
To deserialize the object, we use a FileInputStream
and an ObjectInputStream
, read the object from the stream using the readObject
method, and cast it to the Car
type.Regenerate response