Java - Writing an Object More Than Once to a Stream

Description

Writing an Object More Than Once to a Stream

Demo

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

public class Main {
  public static void main(String[] args) {
    String fileName = "mutableperson.ser";

    serialize(fileName);//from  w ww . j  ava 2 s  .  c  o  m

    deserialize(fileName);
  }

  public static void serialize(String fileName) {
    MutablePerson a = new MutablePerson("A", "V", 6.7);

    File fileObject = new File(fileName);
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
        fileObject))) {

      System.out.println("Objects are written to "
          + fileObject.getAbsolutePath());
      oos.writeObject(a);
      System.out.println(a); // Display what we wrote

      a.setName("book2s.com");
      a.setHeight(6.9);

      oos.writeObject(a);
      System.out.println(a); // display what we wrote again

    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }

  public static void deserialize(String fileName) {
    // personmutable.ser file must exist in the current directory
    File fileObject = new File(fileName);

    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        fileObject))) {

      // Read the two objects that were written in the serialize() method
      MutablePerson john1 = (MutablePerson) ois.readObject();
      MutablePerson john2 = (MutablePerson) ois.readObject();

      // Display the objects
      System.out.println("Objects are read from "
          + fileObject.getAbsolutePath());
      System.out.println(john1);
      System.out.println(john2);
    } catch (IOException | ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
}

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

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

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setHeight(double height) {
    this.height = height;
  }

  public double getHeight() {
    return height;
  }

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

Result

Related Topic