Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java - ObjectInputStream readObject() method



Description

The Java ObjectInputStream readObject() method read an object from the ObjectInputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are read. Default deserializing for a class can be overridden using the writeObject and readObject methods. Objects referenced by this object are read transitively so that a complete equivalent graph of objects is reconstructed by readObject.

The root object is completely restored when all of its fields and the objects it references are completely restored. At this point the object validation callbacks are executed in order based on their registered priorities. The callbacks are registered by objects (in the readObject special methods) as they are individually restored.

Exceptions are thrown for problems with the InputStream and for classes that should not be deserialized. All exceptions are fatal to the InputStream and leave it in an indeterminate state; it is up to the caller to ignore or recover the stream state.

Declaration

Following is the declaration for java.io.ObjectInputStream.readObject() method −

public final Object readObject()

Parameters

NA

Return Value

This method returns the object read from the stream.

Exception

  • ClassNotFoundException − Class of a serialized object cannot be found.

  • InvalidClassException − Something is wrong with a class used by serialization.

  • StreamCorruptedException − Control information in the stream is inconsistent.

  • OptionalDataException − Primitive data was found in the stream instead of objects.

  • IOException − Any of the usual Input/Output related exceptions.

Example - Usage of ObjectInputStream readObject() method

The following example shows the usage of Java ObjectInputStream readObject() 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) {
      String s = "Hello World";
      byte[] b = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};
      
      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.writeObject(s);
         oout.writeObject(b);
         oout.flush();

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

         // read and print an object and cast it as string
         System.out.println("" + (String) ois.readObject());

         // read and print an object and cast it as string
         byte[] read = (byte[]) ois.readObject();
         String s2 = new String(read);
         System.out.println("" + s2);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Output

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

Hello World
example

Example - Reading Fields along with Missing Fields

The following example shows the usage of Java ObjectInputStream readObject() method. This example shows how to serialize and deserialize a single object using readObject().

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;
   }

   public void display() {
      System.out.println("Name: " + name + ", Age: " + age);
   }
}

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      String filename = "personData.ser";

      // Writing an object to a file
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         Person person = new Person("Alice", 25);
         oos.writeObject(person);
         System.out.println("Object written to file.");
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Reading the object from the file
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         Person readPerson = (Person) ois.readObject();
         System.out.println("Object read from file:");
         readPerson.display();
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Object written to file.
Object read from file:
Name: Alice, Age: 25

Explanation

  • The Person class implements Serializable so that it can be serialized.

  • The ObjectOutputStream writes a Person object (Alice, 25) to a file (personData.ser).

  • The ObjectInputStream reads the object back using readObject(), and we cast it to Person.

  • The deserialized object's data is displayed using the display() method.

Example - Reading Multiple Objects from a File

The following example shows the usage of Java ObjectInputStream readObject() method. This example demonstrates writing and reading multiple objects using readObject().

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;
import java.util.ArrayList;
import java.util.List;

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

   public Student(String name, int id) {
      this.name = name;
      this.id = id;
   }

   public void display() {
      System.out.println("Student Name: " + name + ", ID: " + id);
   }
}

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      String filename = "studentsData.ser";

      // Writing multiple objects to a file
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         List<Student> students = new ArrayList<>();
         students.add(new Student("John", 101));
         students.add(new Student("Emma", 102));
         students.add(new Student("David", 103));

         oos.writeObject(students);
         System.out.println("Student objects written to file.");
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Reading the list of objects from the file
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
         List<Student> readStudents = (List<Student>) ois.readObject();
         System.out.println("Student objects read from file:");
         for (Student s : readStudents) {
            s.display();
         }
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Student objects written to file.
Student objects read from file:
Student Name: John, ID: 101
Student Name: Emma, ID: 102
Student Name: David, ID: 103

Explanation

  • The Student class is made serializable.

  • A list of Student objects is created and written to a file (studentsData.ser) using writeObject().

  • readObject() is used to retrieve the list from the file.

  • The retrieved list is iterated, and each student's details are displayed.

java_io_objectinputstream.htm
Advertisements