Java ObjectInputStream read Serializable object from file

Description

Java ObjectInputStream read Serializable object from file

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

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

  public Code(String name, String p, double height) {
    this.name = name;
    this.part = p;
    this.height = height;
  }//from   w w w .  j  av a2  s. com

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

public class Main {
  public static void main(String[] args) {
    Code a = new Code("HTML", "Tag", 6.7);
    Code b = new Code("Java", "Object", 5.7);
    Code c = new Code("C++", "function", 5.4);

    File fileObject = new File("person.dat");

    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();
    }

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

      // Read (or deserialize) the three objects
      a = (Code) ois.readObject();
      b = (Code) ois.readObject();
      c = (Code) 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();
    }
  }
}



PreviousNext

Related