ObjectInputStream in Java | Methods, Example

Object Streams in Java

So far, we have learned to read and write characters, bytes, strings, and primitive data type values from a text file.

It is also possible to perform read and write operations on objects using object streams.

The object streams are constructed using ObjectInputStream and ObjectOutputStream classes.

In this case, we declare data fields as objects and use ObjectInputStream and ObjectOutputStream classes to read and write these objects from files. This process is called object serialization.

ObjectInputStream in Java


ObjectInputStream in Java is an input stream that reads serialized objects from a file. It is responsible for reading objects, primitive type values, and strings from a byte stream.

In other words, an ObjectInputStream is an input stream that deserializes primitive type values, strings, and objects from a stream that was previously written in a file using an ObjectOutputStream.

Since Java ObjectInputStream contains all the methods of DataInputStream, we can perform input operations for objects in addition to primitive type values and strings.

DataInputStream enables to perform input operations for primitive type values and strings. So, we can replace DataInputStream completely with ObjectInputStream.

Java ObjectInputStream class declaration


ObjectInputStream class extends InputStream and implements ObjectInput and ObjectStreamConstants interfaces. The general syntax to declare ObjectInputStream class in java is as follows:

public class ObjectInputStream
   extends InputStream
       implements ObjectInput, ObjectStreamConstants

ObjectInputStream class also implements Closeable, DataInput, ObjectInput, ObjectStreamConstants, and AutoCloseable interfaces. The inheritance diagram for ObjectInputStream class is as below:

java.lang.Object
     java.io.InputStream
         java.io.ObjectInputStream

ObjectInput Interface in Java

ObjectInput in Java is an interface that extends the DataInput and AutoCloseable interfaces. It supports object serialization in java and defines the readObject() method for deserializing an object.


The general syntax to declare ObjectInput interface in java is as below:

public interface ObjectInput
        extends DataInput, AutoCloseable

ObjectInput Interface Methods in Java


In addition to methods inherited from DataInput interface, ObjectInput interface also defines some useful methods that are as follows:

1. int available(): This method returns the number of bytes that are now available to read the input buffer.

2. void close(): This method is used to close the invoking input stream.

3. int read(): This method reads a byte of data. It returns an integer form of the next available byte of input. –1 is returned when the end of the file is met.

4. int read(byte[ ] b): It reads into an array of bytes.

5. int read(byte[ ] b, int off, int len): It reads into an array of bytes.

6. Object readObject(): This method is used to read and return an object from invoking stream.

7. long skip(long n): This method skips n bytes of input.

All the methods defined in ObjectInput interface can throw IOException when an I/O error occurs. The readObject( ) method can also throw an exception named ClassNotFoundException.

Constructors of ObjectInputStream class


ObjectInputStream class provides two constructors with public and protected access modifiers in Java. They are as follows:

1. ObjectInputStream(InputStream inStream): This constructor creates an ObjectInputStream object that reads serialized objects from the specified InputStream inStream. It throws an IOException if an I/O error occurs such as the file is not opening.

The general syntax to create an ObjectInputStream object in java is as follows:

ObjectInputStream ois = new ObjectInputStream(InputStream inStream);

For example:
File file = new File("D:\\objfile.txt");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);

Thus, we can wrap an ObjectInputStream on any InputStream using this constructor.

2. protected ObjectInputStream(): This constructor creates an ObjectInputStream object.

ObjectInputStream Methods in Java


In addition to methods inherited from InputStream, ObjectInputStream class also defines some useful methods to perform input operations on objects. They are as follows:


1. int available(): This method is used to retrieve the number of bytes available to read in the input buffer.

2. void close(): This method is used to close the input stream.

3. void defaultReadObject(): This method reads the non-static and non-transient data fields of the current class from the stream.

4. protected boolean enableResolveObject(boolean enable): It is used to enable the stream to allow objects read from the stream to be replaced.

5. int read(): This method is used to read a byte of data.


6. int read(byte[ ] buf, int off, int len): This method reads into an array of bytes.

7. boolean readBoolean(): This method reads and returns a boolean value from the invoking stream.

8. byte readByte(): This method reads and returns an 8-bit byte from the invoking stream.

9. char readChar(): This method reads and returns a 16-bit char from the invoking stream.

10. protected ObjectStreamClass readClassDescriptor(): This method is used to read a class descriptor from the serialization stream.


11. double readDouble(): This method reads and returns a 64 bit double from the invoking stream.

12. ObjectInputStream.GetField readFields(): This method reads the persistent data fields from the stream and makes them available by name.

13. float readFloat(): This method reads and returns a 32-bit float from the invoking stream.

14. int readInt( ): It reads and returns a 32-bit int from the invoking stream.

15. long readLong( ): It reads and returns a 64 bit long from the invoking stream.


16. final Object readObject( ): The readObject() method reads and returns an object from the invoking stream.

17. short readShort( ): The readShort() method reads and returns a short from the invoking stream.

18. void readFully(byte[ ] buf): The readFully() method reads bytes, blocking until all bytes are read.

19. void readFully(byte[ ] buf, int off, int len): This overloaded readFully() method reads bytes, blocking until all bytes are read.

20. int readUnsignedByte( ): The readUnsignedByte() method reads and returns a 8 bit unsigned byte from the invoking stream.


21. int readUnsignedShort( ): The readUnsignedShort reads and returns a 16 bit unsigned short from the invoking stream.

22. String readUTF(): The readUTF() method reads a String in modified UTF-8 format.

23. int skipBytes(int lenBytes): It skips lenBytes bytes in the invoking stream, returning the number of bytes actually skipped.

24. protected void readStreamHeader(): This method allows subclasses to read and verify their own stream headers.

25. Object readUnshared(): The readUnshared() method reads an “unshared” object from the ObjectInputStream.


All these methods of ObjectInputStream class can throw IOException if I/O errors occur while reading from the underlying InputStream.

If the end of file is reached then EOFException can be thrown.

ObjectInputStream Example Programs


Let’s take an example program where we will write student name, roll no, marks, percentage, and the current data to a file named objfile.txt and then will read these data using ObjectOutputStream and ObjectInputStream classes respectively.

Program source code 1:

package javaProgram;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

public class TestObjectInputStream {
public static void main(String[] args) throws IOException, ClassNotFoundException 
{
// Create an file output stream for file object.txt.
     FileOutputStream fos = new FileOutputStream("D:\\objfile.txt");
  
// Create an ObjectOutputStream object and pass reference fos to its constructor.
     ObjectOutputStream oos = new ObjectOutputStream(fos);

// Write a string, int values, double value and object to the file.
     oos.writeUTF("Shubh");
     oos.writeInt(10);
     oos.writeInt(484);
     oos.writeDouble(96.55);
     oos.writeObject(new java.util.Date());	
	
	
// Create an FileInputStream object for the objfile.txt.
     FileInputStream fis = new FileInputStream("D:\\objfile.txt");	

// Create an InputStreamObject instance and pass object reference variable fis to its constructor.
     ObjectInputStream ois = new ObjectInputStream(fis);
   
// Read a string, int values, double value and object to the file.
     String name = ois.readUTF();
     int rollNo = ois.readInt();
     int marksObt = ois.readInt();
     double per = ois.readDouble();
     Date date = (Date) ois.readObject(); // Casting into date.
  
// Display data read on the console.
     System.out.println("Name: " +name);
     System.out.println("Roll no: " +rollNo);
     System.out.println("Total marks obtained: " +marksObt);
     System.out.println("Percentage: " +per+ "%");
     System.out.println("Date: " +date);

    oos.close();
    ois.close();
  }
}
Output:
          Name: Shubh
          Roll no: 10
          Total marks obtained: 484
          Percentage: 96.55%
          Date: Thu Aug 05 09:00:44 IST 2021

Explanation:

1. In this example program, an ObjectOutputStream instance is created to write data into the object.txt file. A string, int values, a double value, and an object are written to the file.

2. To improve performance, we may add a buffer in the stream using the following statements:

FileOutputStream fos = new FileOutputStream("D:\\objfile.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);

Or, in a single line:
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("D:\\objfile.txt")));

3. Multiple objects or primitive type values can be written to the output stream. The objects must be read back from the analogous ObjectInputStream with the same types and in the same order as they were written in the objfile.txt file.

4. The readObject() method of ObjectInputStream throws an exception named ClassNotFoundException because when JVM restores an object, it first loads the class for the object if the class has not been loaded.

Since ClassNotFoundException is a checked exception, the main method declares to throw it.

5. An ObjectInputStream instance is created to read input from the objfile.txt file. We have to read the data from the file in the same order and format as they were written to the file.

6. A string, int values, a double value, and an object are read from the file. Since readObject() method returns an Object, therefore, it is cast into Date and assigned to a variable date of type Date.


Hope that this tutorial has covered almost all the important points related to ObjectInputStream class in Java with example program. I hope that you will have understood the basic concepts of ObjectInputStream class.

In the next tutorial, we will learn ObjectOutput and ObjectOutputStream in Java.

Thanks for reading!!!