Java ObjectInputStream

In this example we will discuss about the Java class ObjectInputStream.

Java ObjectInputStream

In this example we will discuss about the Java class ObjectInputStream.

Java ObjectInputStream

Java ObjectInputStream

In this example we will discuss about the Java class ObjectInputStream.

ObjectInputStream class of java.io package is used to read the objects written previously into the output stream by ObjectOutputStream. ObjectOutputStream stores the objects as a graph of objects. ObjectInputStream can deserializes only those objects which have a support of java.io.Serializable or java.io.Externalizable interface. ObjectInputStream class has a method readObject() which reads an object from the stream. To read arrays and strings it is required to cast these to the expected type because the strings and arrays are objects in Java and are handled as objects on serialization and to read the primitive data types from the stream methods of DataInput can be used.

Constructors of ObjectInputStream

Constructor
Description
ObjectInputStream() This is a default constructor which is implemented by the subclasses in a way to not have to allocate private data.
Syntax : protected ObjectInputStream() throws IOException, SecurityException
ObjectInputStream(InputStream in) This is a parameterized constructor which is used to create an object of ObjectInputStream that contains the reference of InputStream from where the data can be read.
Syntax :public ObjectInputStream(InputStream in) throws IOException

Methods of ObjectInputStream

commonly used methods of ObjectInputStream class are as follows :

  • readObject() : Objects from the ObjectInputStrem is read by this method.

    Syntax : public final Object readObject() throws IOException, ClassNotFoundException
     
  • available() : How many bytes can be read from the input stream is returned by this method.

    Syntax : public int available() throws IOException
     
  • close() : This method is used to close the input stream. This method is also called for release the resources associated with the stream.

    Syntax : public void close() throws IOException
     
  • read() : Single byte of data is read from the strem by this method.

    Syntax : public int read() throws IOException
     
  • read(byte[] buf, int off, int len) : This method is used to read the specified length of byte 'len', started from the offset 'off' from the specified array of byte 'b'.

    Syntax : public int read(byte[] buf, int off,int len) throws IOException
     
  • readBoolean() : This method is used to read boolean from the stream.

    Syntax : public boolean readBoolean() throws IOException
     
  • readByte() : This method is used to read 8 bit byte from the stream.

    Syntax : public byte readByte() throws IOException
     
  • readChar() : This method is used to read 16 bit char from the stream.

    Syntax : public char readChar() throws IOException
     
  • readDouble() : This method is used to read 64 bit double from the stream.

    Syntax : public double readDouble() throws IOException
     
  • readFloat() : This method is used to read 32 bit float from the stream.

    Syntax : public float readFloat() throws IOException
     
  • readInt() : This method is used to read 32 bit int from the stream.

    Syntax : public int readInt() throws IOException
     
  • readLong() : This method is used to read 64 bit long from the stream.

    Syntax : public long readLong() throws IOException
     
  • readShort() : This method is used to read 16 bit short from the stream.

    Syntax : public short readShort() throws IOException
     
  • readUnsignedByte() : This method is used to read unsigned 8 bit byte from the stream.

    Syntax : public int readUnsignedByte() throws IOException
     
  • readUnsignedShort() : This method is used to read unsigned 16 bit short from the stream.

    Syntax : public int readUnsignedShort() throws IOException
     
  • readUTF() : This method is used to read string in modified UTF-8 format from the stream.

    Syntax : public String readUTF() throws IOException
     
  • skipBytes(int len) : This method is used to skip the specified number of bytes from the stream.

    Syntax : public int skipBytes(int len) throws IOException

Example :

An example is being given here will demonstrate you about how to use the java.io.ObjectInputStream class to read the objects from the input stream. To read the objects from the object input stream objects should be written by the object output stream. So in this example before reading the objects from the input stream it is required to write the objects first to the output stream. So here I have created a Java Bean named Employee and created a class EmployeeRecord for writing Employee object to the output stream then created a class ObjectInputStream for reading the objects.

Source Code

Employee.java

import java.io.Serializable;

public class Employee implements Serializable {
    
    private String name;
    private String dept;
    private int salary;
    
    public Employee() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
   
   public String toString() {        
        
        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        sb.append(name);
        sb.append("\t");
        sb.append(dept);
        sb.append("\t");
        sb.append(salary);
        sb.append("\n");
        
        return sb.toString();
    }    
    
}

EmployeeRecord.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class EmployeeRecord
{
    public static void main(String args[])
     {
        
        ObjectOutputStream oos = null;
        
        try
          {
             FileOutputStream fos = new FileOutputStream("employee.txt");
            
             oos = new ObjectOutputStream(fos);
            
             Employee emp = new Employee();
             emp.setName("Shashi");
             emp.setDept("Content Writing");
             emp.setSalary(20000);
            
             oos.writeObject(emp);
            
             Employee emp1 = new Employee();
            
             emp1.setName("Amit");
             emp1.setDept("Content Writing");
             emp1.setSalary(18000);
            
             oos.writeObject(emp1);
            
            System.out.println("objects written successfully");
        }
     catch (FileNotFoundException fex)
       {
            System.out.println(fex);
       }
     catch (Exception ex)
      {
            System.out.println(ex);
      }
     finally
      {
          try
           {
                if (oos != null)
                 {
                     oos.close();
                 }
            }
         catch (Exception ex1)
           {
                System.out.println(ex1);
            }
       }
    }       
}

ObjectInputStreamExample.java

import java.io.*;

public class ObjectInputStreamExample 
{    
    public static void main(String args[])
     {
        
        ObjectInputStream ois = null;
        
        try
          {
             FileInputStream fis = new FileInputStream("employee.txt");
             ois = new ObjectInputStream(fis);
            
             Object obj = null;
            
             System.out.println("Name \t"+"Department \t"+"Salary");
             while ((obj = ois.readObject()) != null)
              {
                
                 if (obj instanceof Employee)
                  {                
                     System.out.println(((Employee)obj).toString());
                  }              
              }       
         
          }
       catch (EOFException ex)
         {
           //This exception will be caught when EOF is reached
            System.out.println("End of file reached.");
         }
       catch (ClassNotFoundException ex)
        {
            System.out.println(ex);
        }
       catch (Exception ex)
        {
            System.out.println(ex);
        }
       finally
        {
            try 
              {
                  if (ois != null)
                   {
                      ois.close();
                   }
              }
            catch (Exception ex) 
              {
                  System.out.println(ex);
              }
         }
    }
}

Output :

First Compiled the EmployeeRecord.java then the output will be as follows :

Now compiled the ObjectInputStreamExample.java then the output will be as follows :

Download Source Code