Read object from a file in Java

Description

The following code shows how to read object from a file.

Example


//w ww  .  j a v  a2 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;
  }
}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip