Java I/O Object Streams

Object Streams Overview

  • The object stream classes are ObjectInputStream and ObjectOutputStream. These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput.
  • Only objects that support the java.io.Serializable interface can be written to streams.

ObjectOutputStream Class

  • An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
  • Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconstituted on another host or in another process.
  • Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.
  • The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputStream with the same types and in the same order as they were written.

ObjectOutputStream Class Example

In this ObjectOutputStreamExample, we are going to serialize the object of Employee class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named employees.txt. Let's create a class Employee which implements the Serializable interface.
package com.javaguides.javaio.fileoperations.examples;

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

public class ObjectOutputStreamExample {

 public static void main(String[] args) {
  final Employee employee = new Employee();
  employee.setId(100);
  employee.setName("ramesh");
         try (final FileOutputStream fout = new FileOutputStream("employees.txt");
   final ObjectOutputStream out = new ObjectOutputStream(fout)) {
   out.writeObject(employee);
   //out.writeInt(12345);
   //out.writeObject("Today");
   //out.writeObject(new Date());
        
   out.flush();
   System.out.println("success");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

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

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

ObjectInputStream Class

  • 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.

ObjectInputStream Class Example

For example to read from a stream as written by the example in ObjectOutputStream:
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
   e.printStackTrace();
  }
 }
}
Output:
printing employee object details
100 ramesh
printing address object details

Learn complete Java I/O on : Java I/O Guide

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

Comments