Java - File Input Output Serializing Objects

Introduction

The following code defines a Person class that implements the Serializable interface.

The Person class contains three fields: name, gender, and height.

It overrides the toString() method and returns the Person description.

The code write Person objects to a person.ser file.

Demo

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

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;
  }//from w w w.j  a  v a  2  s.c o  m

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

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

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

    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
        fileObject))) {

      // 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 e) {
      e.printStackTrace();
    }
  }
}

Result

Related Topic