ObjectInputStream Class in Java

  • An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.
  • ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.
  • ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.
  • Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams.
  • The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java, strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the expected type.
  • Primitive data types can be read from the stream using the appropriate method on DataInput.
  • The below class diagram shows a list of methods that ObjectInputStream provides.

ObjectInputStream class Methods

ObjectInputStream class Constructors

  • protected ObjectInputStream() - Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.
  • ObjectInputStream(InputStream in) - Creates an ObjectInputStream that reads from the specified InputStream.

ObjectInputStream class Example

For example to read from a stream as written by the example in ObjectOutputStream.
This example uses the try-with-resources statement to close the resources automatically.
package com.javaguides.javaio.fileoperations.examples;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class ObjectInputStreamExample {
 public static void main(String[] args) {
  try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employees.txt"))) {
   final Employee employee = (Employee) in.readObject();
   System.out.println(" printing employee object details");
   System.out.println(employee.getId() + " " + employee.getName());

   System.out.println(" printing address object details");
  } catch (IOException | ClassNotFoundException e) {
   // TODO Auto-generated catch block
 printing employee object details
100 ramesh
 printing address object details


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course