ObjectInputStream class

ObjectInput interface

The ObjectInput interface extends the DataInput interface and defines the methods shown in the following table.

int available( )
Returns the number of bytes that are now available in the input buffer.
void close( )
Closes the invoking stream.
int read( )
Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered.
int read(byte buffer[ ])
Read up to buffer.length bytes into buffer, returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered.
int read(byte buffer[ ], int offset, int numBytes)
Read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered.
Object readObject( ) throw ClassNotFoundException
Reads an object from the invoking stream.
long skip(long numBytes)
Skips numBytes bytes in the invoking stream, returning the number of bytes actually ignored.

The ObjectInputStream class extends the InputStream class and implements the ObjectInput interface. ObjectInputStream is responsible for reading objects from a stream.

ObjectInputStream supports object serialization through the readObject( ) method. readObject( ) method is called to deserialize an object.

A constructor of this class is

ObjectInputStream(InputStream inStream) throws IOException
inStream is the input stream from which serialized objects should be read.

Methods from ObjectInputStream:

int available()
Returns the number of bytes that can be read without blocking.
void close()
Closes the input stream.
void defaultReadObject()
Read the non-static and non-transient fields of the current class from this stream.
int read()
Reads a byte of data.
int read(byte[] buf, int off, int len)
Reads into an array of bytes.
boolean readBoolean()
Reads in a boolean.
byte readByte()
Reads an 8 bit byte.
char readChar()
Reads a 16 bit char.
double readDouble()
Reads a 64 bit double.
float readFloat()
Reads a 32 bit float.
void readFully(byte[] buf)
Reads bytes, blocking until all bytes are read.
void readFully(byte[] buf, int off, int len)
Reads bytes, blocking until all bytes are read.
int readInt()
Reads a 32 bit int.
String readLine()
Deprecated. This method does not properly convert bytes to characters. see DataInputStream for the details and alternatives.
long readLong()
Reads a 64 bit long.
Object readObject()
Read an object from the ObjectInputStream.
short readShort()
Reads a 16 bit short.
Object readUnshared()
Reads an "unshared" object from the ObjectInputStream.
int readUnsignedByte()
Reads an unsigned 8 bit byte.
int readUnsignedShort()
Reads an unsigned 16 bit short.
String readUTF()
Reads a String in modified UTF-8 format.
void registerValidation(ObjectInputValidation obj, int prio)
Register an object to be validated before the graph is returned.
int skipBytes(int len)
Skips bytes.

Revised from Open JDK source code

The following code show to use ObjectOutputStream to read and write primitive data.


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;

public class Main {
  static final String dataFile = "data.dat";

  public static void main(String[] args) throws IOException, ClassNotFoundException {

    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

      out.writeObject(new BigInteger("123"));
      out.writeInt(123);
      out.writeUTF("a String");
    } finally {
      out.close();
    }

    ObjectInputStream in = null;
    try {
      in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
      try {
        while (true) {
          BigInteger price = (BigInteger) in.readObject();
          int unit = in.readInt();
          String desc = in.readUTF();
          System.out.println(price);
          System.out.println(unit);
          System.out.println(desc);
        }
      } catch (EOFException e) {
      }

    } finally {
      in.close();
    }
  }
}

The output:


123
123
a String

The following code shows how to use the ObjectInputStream and ObjectOutputStream to do the object serialization.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
  public static void main(String args[]) throws Exception{
      MyClass object1 = new MyClass("Hello", -1, 2.1);
      System.out.println("object1: " + object1);
      FileOutputStream fos = new FileOutputStream("serial");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(object1);
      oos.flush();
      oos.close();

      FileInputStream fis = new FileInputStream("serial");
      ObjectInputStream ois = new ObjectInputStream(fis);
      MyClass object2 = (MyClass) ois.readObject();
      ois.close();
      System.out.println("object2: " + object2);
  }
}

class MyClass implements Serializable {
  String s;
  int i;
  double d;

  public MyClass(String s, int i, double d) {
    this.s = s;
    this.i = i;
    this.d = d;
  }

  public String toString() {
    return "s=" + s + "; i=" + i + "; d=" + d;
  }
}
Home 
  Java Book 
    File Stream