Java Serializable implement

Description

Java Serializable implement

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   w  ww  .  j  a 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);

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

      // Display the serialized objects on the standard output
      System.out.println(a);

      // Print the output path
      System.out.println("Objects were written to "
          + fileObject.getAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related