Create ObjectOutputStream out of FileOutputStream : ObjectOutputStream « File « Java Tutorial






import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

public class ObjectWriter {
  public static void main(String[] arguments) {
    Message mess = new Message();
    String author = "London";
    String recipient = "G, B";
    String[] letter = { "Merry Christmas." };
    Date now = new Date();
    mess.writeMessage(author, recipient, now, letter);
    try {
      FileOutputStream fo = new FileOutputStream("Message.obj");
      ObjectOutputStream oo = new ObjectOutputStream(fo);
      oo.writeObject(mess);
      oo.close();
      System.out.println("Object created successfully.");
    } catch (IOException 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.23.ObjectOutputStream
11.23.1.Create ObjectOutputStream out of FileOutputStream
11.23.2.Writing objects to file with ObjectOutputStream
11.23.3.Serializing an Object (JButton)
11.23.4.Reading Basic Data From an Object Stream
11.23.5.Create a serialized output file.
11.23.6.Try to recover a serialized file without the class of object that's stored in that file
11.23.7.Object IO
11.23.8.illustrates serialization and deserialization