Java - Externalizable Object Serialization

Introduction

The following code shows you how to serialize and deserialize Externalizable objects.

Person class implements the Externalizable interface.

Demo

import java.io.Externalizable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Main {
  public static void main(String[] args) {
    // Create three Person objects
    PersonExt a = new PersonExt("A", "X", 6.7);
    PersonExt b = new PersonExt("B", "Y", 5.7);
    PersonExt c = new PersonExt("C", "Z", 5.4);

    // The output file
    File fileObject = new File("personext.ser");

    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
        fileObject))) {//  w w w .ja  va 2s  .c  o m

      // Write (or serialize) the objects to the object output stream
      oos.writeObject(a);
      oos.writeObject(b);
      oos.writeObject(c);

      // Display the serialized objects on the standard output
      System.out.println(a);
      System.out.println(b);
      System.out.println(c);
      // Print the output path
      System.out.println("Objects were written to "
          + fileObject.getAbsolutePath());
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
}

class PersonExt implements Externalizable {
  private String name = "Unknown";
  private String gender = "Unknown";
  private double height = Double.NaN;

  public PersonExt() {
  }

  public PersonExt(String name, String gender, double height) {
    this.name = name;
    this.gender = gender;
    this.height = height;
  }

  // Override the toString() method to return the person description
  public String toString() {
    return "Name: " + this.name + ", Gender: " + this.gender + ", Height: "
        + this.height;
  }

  public void readExternal(ObjectInput in) throws IOException,
      ClassNotFoundException {
    // Read name and gender in the same order they were written
    this.name = in.readUTF();
    this.gender = in.readUTF();
  }

  public void writeExternal(ObjectOutput out) throws IOException {
    // we write only the name and gender to the stream
    out.writeUTF(this.name);
    out.writeUTF(this.gender);
  }
}

Result

Related Topic