Create ObjectInputStream from FileInputStream : ObjectInputStream « File « Java Tutorial






import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;

public class ObjectReader {
  public static void main(String[] arguments) {
    try {
      FileInputStream fi = new FileInputStream("message.obj");
      ObjectInputStream oi = new ObjectInputStream(fi);
      Message mess = (Message) oi.readObject();
      System.out.println("Message:\n");
      System.out.println("From: " + mess.from);
      System.out.println("To: " + mess.to);
      System.out.println("Date: " + mess.when + "\n");
      for (int i = 0; i < mess.lineCount; i++)
        System.out.println(mess.text[i]);
      oi.close();
    } catch (Exception e) {
      System.out.println("Error " + e.toString());
    }
  }
}

class Message implements Serializable {
  int lineCount;

  String from, to;

  Date when;

  String[] text;

  void writeMessage(String inFrom, String inTo, Date inWhen, String[] inText) {

    text = new String[inText.length];
    for (int i = 0; i < inText.length; i++)
      text[i] = inText[i];
    lineCount = inText.length;
    to = inTo;
    from = inFrom;
    when = inWhen;
  }
}








11.22.ObjectInputStream
11.22.1.Create ObjectInputStream from FileInputStream
11.22.2.Reading objects from file using ObjectInputStream
11.22.3.Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.
11.22.4.Store objects in file