Java ObjectOutputStream write Serializable object to file

Description

Java ObjectOutputStream write Serializable object to file

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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   www.ja  v  a 2  s. c  o m*/

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



PreviousNext

Related