Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Java - ObjectInputStream Class



Introduction

The Java ObjectInputStream class deserializes primitive data and objects previously written using an ObjectOutputStream. Following are the important points about BufferedInputStream −

  • It is used to recover those objects previously serialized. It 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.

Class declaration

Following is the declaration for Java.io.ObjectInputStream class −

public class ObjectInputStream
   extends InputStream
      implements ObjectInput, ObjectStreamConstants

Class constructors

Sr.No. Constructor & Description
1

protected ObjectInputStream()

This provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.

2

ObjectInputStream(InputStream in)

This creates an ObjectInputStream that reads from the specified InputStream.

Class methods

Sr.No. Method & Description
1 int available()

This method returns the number of bytes that can be read without blocking.

2 void close()

This method closes the input stream.

3 void defaultReadObject()

This method reads the non-static and non-transient fields of the current class from this stream.

4 protected boolean enableResolveObject(boolean enable)

This method enables the stream to allow objects read from the stream to be replaced.

5 int read()

This method reads 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 in a boolean.

8 byte readByte()

This method reads an 8 bit byte.

9 char readChar()

This method r a 16 bit char.

10 protected ObjectStreamClass readClassDescriptor()

This method read a class descriptor from the serialization stream.

11 double readDouble()

This method reads a 64 bit double.

12 ObjectInputStream.GetField readFields()

This method reads the persistent fields from the stream and makes them available by name.

13 float readFloat()

This method reads a 32 bit float.

14 void readFully(byte[] buf)

This method reads bytes, blocking until all bytes are read.

15 void readFully(byte[] buf, int off, int len)

This method reads bytes, blocking until all bytes are read.

16 int readInt()

This method reads a 32 bit int.

17 long readLong()

This method reads a 64 bit long.

18 Object readObject()

This method reads an object from the ObjectInputStream.

19 protected Object readObjectOverride()

This method is called by trusted subclasses of ObjectOutputStream that constructed ObjectOutputStream using the protected no-arg constructor.

20 short readShort()

This method reads a 16 bit short.

21 protected void readStreamHeader()

This method is provided to allow subclasses to read and verify their own stream headers.

22 Object readUnshared()

This method reads an "unshared" object from the ObjectInputStream.

23 int readUnsignedByte()

This method reads an unsigned 8 bit byte.

24 int readUnsignedShort()

This method reads an unsigned 16 bit short.

25 String readUTF()

This method reads a String in modified UTF-8 format.

26

void registerValidation(ObjectInputValidation obj, int prio)

This method register an object to be validated before the graph is returned.

27 protected Class<?> resolveClass(ObjectStreamClass desc)

This method loads the local class equivalent of the specified stream class description.

28 protected Object resolveObject(Object obj)

This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization.

29 protected Class<?> resolveProxyClass(String[] interfaces)

This method returns a proxy class that implements the interfaces named in a proxy class descriptor; subclasses may implement this method to read custom data from the stream along with the descriptors for dynamic proxy classes, allowing them to use an alternate loading mechanism for the interfaces and the proxy class.

30 int skipBytes(int len)

This method skips bytes.

Methods inherited

This class inherits methods from the following classes −

  • Java.io.InputStream
  • Java.io.Object
  • Java.io.ObjectInput

Example - Usage of ObjectInputStream available() method

The following example shows the usage of Java ObjectInputStream available() method.

ObjectInputStreamDemo.java

package com.tutorialspoint;

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

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeUTF("Hello World");
         oout.flush();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois =  new ObjectInputStream(new FileInputStream("test.txt"));

         // check how many bytes are available
         System.out.println("" + ois.available());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
      
   }
}

Output

Let us compile and run the above program, this will produce the following result−

13

Example - Closing an ObjectInputStream After Reading an Object

The following example shows the usage of Java ObjectInputStream close() method. This example writes an object to a file, reads it using ObjectInputStream, and then closes the stream.

ObjectInputStreamDemo.java

package com.tutorialspoint;

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

class Person implements Serializable {
   private static final long serialVersionUID = 1L;
   String name;
   int age;

   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }

   @Override
   public String toString() {
      return "Person{name='" + name + "', age=" + age + "}";
   }
}

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      try {
         // Serialize object to file
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"));
         oos.writeObject(new Person("Alice", 30));
         oos.close();

         // Read object from file
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"));
         Person person = (Person) ois.readObject();
         System.out.println("Read Object: " + person);

         // Close the ObjectInputStream
         ois.close();

         // Trying to read again after closing
         System.out.println("Trying to read again...");
         ois.readObject(); // This will throw an IOException

      } catch (IOException | ClassNotFoundException e) {
         System.out.println("Exception: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Read Object: Person{name='Alice', age=30}
Trying to read again...
Exception: Stream Closed

Explanation

  • Writes a Person object to a file (person.dat).

  • Reads the object using ObjectInputStream.

  • Closes the stream using ois.close().

  • Attempts to read again after closing, which throws an IOException: Stream Closed.

Example - Using defaultReadObject() for Basic Serialization

The following example shows the usage of Java ObjectInputStream defaultReadObject() method. This example demonstrates default serialization using defaultReadObject()

ObjectInputStreamDemo.java

package com.tutorialspoint;

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

class Person implements Serializable {
   private static final long serialVersionUID = 1L;
   String name;
   int age;

   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
   
   private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
      ois.defaultReadObject(); // Restores default serialized fields
   }

   @Override
   public String toString() {
      return "Person{name='" + name + "', age=" + age + "}";
   }
}

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      try {
         // Serialize object
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"));
         oos.writeObject(new Person("Alice", 30));
         oos.close();

         // Deserialize object
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"));
         Person person = (Person) ois.readObject();
         ois.close();

         System.out.println("Deserialized Object: " + person);
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Deserialized Object: Person{name='Alice', age=30}

Explanation

  • The Person object is serialized and written to person.dat.

  • During deserialization, defaultReadObject() restores the name and age fields.

  • The deserialized object is printed correctly.

Advertisements