Java - File Input Output Deserializing Objects

Introduction

The following code demonstrates how to read objects from the person.ser file.

Demo

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class Main {
  public static void main(String[] args) {
    // The input file
    File fileObject = new File("person.ser");

    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        fileObject))) {/*  www .j a  va  2s.  c  o m*/

      // Read (or deserialize) the three objects
      Person a = (Person) ois.readObject();
      Person b = (Person) ois.readObject();
      Person c = (Person) 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 Person implements Serializable {
  private String name = "Unknown";
  private String gender = "Unknown";
  private double height = Double.NaN;

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

  @Override
  public String toString() {
    return "Name: " + this.name + ", Gender: " + this.gender + ", Height: "
        + this.height;
  }
}

Result

Related Topic