Java ObjectOutputStream write Externalizable object to file

Description

Java ObjectOutputStream write Externalizable object to file


import java.io.Externalizable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

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

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

    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
        fileObject))) {//ww w  .j  a va  2 s.  co  m

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

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

  public Code() {
  }

  public Code(String name, String p, double height) {
    this.name = name;
    this.part = p;
    this.height = height;
  }

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

  public void readExternal(ObjectInput in) throws IOException,
      ClassNotFoundException {
    this.name = in.readUTF();
    this.part = in.readUTF();
  }

  public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(this.name);
    out.writeUTF(this.part);
  }
}



PreviousNext

Related