ObjectOutputStream Class in Java

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

  • protected ObjectOutputStream() - Provide a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream.
  • ObjectOutputStream(OutputStream out) - Creates an ObjectOutputStream that writes to the specified OutputStream.

ObjectOutputStream class Methods

This class diagram shows a list of methods ObjectOutputStream class provides in Java.

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.
This example uses the try-with-resources statement to close the resources automatically.
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;
 }
}

Reference

Comments