How do you use ObjectInputStream/ObjectOutputStream with a simple code example?

The ObjectInputStream and ObjectOutputStream classes in Java are used to serialize and deserialize objects. Serialization is the process of converting an object into a byte stream, making it possible to save the object's state to a file or transmit it over a network. Deserialization is the reverse process of converting the byte stream back into a copy of the object.

Here's a simple example to demonstrate how to use these classes:

import java.io.*; // Class to be serialized class Person implements Serializable { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class Example { public static void main(String[] args) { // Serialize the object Person person = new Person("Alice", 30); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) { oos.writeObject(person); } catch (IOException e) { e.printStackTrace(); } // Deserialize the object Person deserializedPerson = null; try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) { deserializedPerson = (Person) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Deserialized Person: " + deserializedPerson); } }

ObjectInputStream ObjectOutputStream serialization deserialization Java