Java Serialization in File Handling

Serialization in Java involves converting an object into a byte stream, which can be written to a file. This allows the object to be saved for later use or transmitted over a network.

Serialization:


import java.io.*;

// Serializable class
class Person implements Serializable {
  private static final long serialVersionUID = 1L;
  private String name;
  private int age;

  // Constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Getters and setters (not shown for brevity)
}

public class SerializationExample {
  public static void main(String[] args) {
    // Create an object to serialize
    Person person = new Person("John", 25);

    // Serialize the object and write to a file
    try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
      outputStream.writeObject(person);
      System.out.println("Serialization completed.");
    } catch (IOException e) {
      System.out.println("Error during serialization: " + e.getMessage());
    }
  }
}

Deserialization:


import java.io.*;

// Serializable class
class Person implements Serializable {
  private static final long serialVersionUID = 1L;
  private String name;
  private int age;

  // Constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Getters and setters (not shown for brevity)
}

public class DeserializationExample {
  public static void main(String[] args) {
    // Deserialize the object from a file
    try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("person.ser"))) {
      Person person = (Person) inputStream.readObject();
      System.out.println("Deserialization completed. Person details: " + person.getName() + ", " + person.getAge());
    } catch (IOException | ClassNotFoundException e) {
      System.out.println("Error during deserialization: " + e.getMessage());
    }
  }
}

Notes:

Serialization and deserialization in Java provide a way to persist and retrieve object state. Classes that need to be serialized must implement the Serializable interface.

When deserializing an object, it's important to handle the ClassNotFoundException that may occur if the class definition of the serialized object is not found.