Java - Deserializing PersonExt Objects That Implement the Externalizable Interface

Description

Deserializing PersonExt Objects That Implement the Externalizable Interface

Demo

import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;

public class Main {
  public static void main(String[] args) {
    File fileObject = new File("personext.ser");
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        fileObject))) {/*from  w w  w  .ja  va2 s.  c  o  m*/

      // Read (or deserialize) the three objects
      PersonExt a = (PersonExt) ois.readObject();
      PersonExt b = (PersonExt) ois.readObject();
      PersonExt c = (PersonExt) ois.readObject();

      // Let's display the objects that are read
      System.out.println(a);
      System.out.println(b);
      System.out.println(c);

      // Print the input path
      System.out.println("Objects were read from "
          + fileObject.getAbsolutePath());
    } catch (FileNotFoundException e) {
      System.out.println(fileObject.getPath());
    } catch (ClassNotFoundException | IOException e) {
      e.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