Java I/O How to - Read Serializable object from a file








Question

We would like to know how to read Serializable object from a file.

Answer

/*ww  w.  j a  va2  s  .  co m*/
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;

public class Main {
  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;
  }
}

The code above generates the following result.