ObjectOutputStream in Java | Methods, Example

ObjectOutputStream in Java is an output stream that writes serialized objects to a text file. It is responsible for writing objects, primitive type values, and strings to a byte stream.

In other words, an ObjectOutputStream is an output stream that serializes primitive type values, strings, and objects to a stream.

Since Java ObjectOutputStream contains all the methods of DataOutputStream, we can perform output operations for objects in addition to primitive type values and strings.

DataOutputStream enables to perform output operations for primitive type values and strings. So, we can replace DataOutputStream completely with ObjectOutputStream.

Java ObjectOutputStream class declaration


ObjectOutputStream class extends OutputStream and implements ObjectOutput and ObjectStreamConstants interfaces. The general syntax to declare ObjectOutputStream class in java is as follows:

public class ObjectOutputStream
    extends OutputStream
         implements ObjectOutput, ObjectStreamConstants

ObjectOutputStream class also implements Closeable, DataOutput, Flushable, ObjectInput, ObjectStreamConstants, and AutoCloseable interfaces.

The inheritance diagram for ObjectOutputStream class is as below:

java.lang.Object
    java.io.OutputStream
        java.io.ObjectOutputStream

ObjectOutput Interface in Java


ObjectOutput in Java is an interface that extends the DataOutput and AutoCloseable interfaces. It supports object serialization in java and defines the writeObject() method for serializing an object.

The general syntax to declare ObjecOutput interface in java is as below:

public interface ObjectOutput
      extends DataOutput, AutoCloseable

ObjectOutput Interface Methods in Java


In addition to methods inherited from DataOutput interface, ObjectOutput interface also defines some useful methods that are as follows:


1. void close(): This method closes the invoking stream. Further write attempts will cause an IOException.

2. void flush(): This method flushes the output stream.

3. void write(byte[ ] b): This method writes an array of bytes to the invoking stream.

4. void write(byte[ ] b, int off, int len): It writes a subarray of bytes.

5. void write(int b): It writes a single byte to the invoking stream. The byte written to the stream is the low-order byte of b.

6. void writeObject(Object obj): The writeObject() method writes an object obj to the underlying storage or stream.

Constructors of ObjectOutputStream class


ObjectOutputStream class provides two constructors with public and protected access modifiers in Java. They are as follows:

1. ObjectOutputStream(OutputStream outStream): This constructor creates an ObjectOutputStream object that writes serialized objects from the specified OutputStream outStream. It throws an IOException if an I/O error occurs.

The general syntax to create an ObjectOutputStream object in java is as follows:

ObjectOutputStream oos = new ObjectOutputStream(OutputStream outStream);

For example:
File file = new File("D:\\objfile.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);

Thus, we can wrap an ObjectOutputputStream on any OutputStream using this constructor.

2. protected ObjectOutputStream(): This constructor creates an ObjectOutputStream object.

ObjectOutputStream Methods in Java


In addition to methods inherited from OutputStream, ObjectOutputStream class also defines some useful methods to perform output operations on objects. They are as follows:


1. void close(): The close() method is used to closing the invoking stream. Further, write tries will cause an IOException.

2. void defaultWriteObject(): The defaultWriteObject() method is used to write the non-static and non-transient fields of the current class to this stream.

3. protected void drain(): The drain() method is used to drain any buffered data in ObjectOutputStream.

4. void flush(): The flush() method is used to flush the stream.

5. ObjectOutputStream.PutField putFields(): The putField() method is used to get the object used to buffer persistent fields to be written to the stream.


6. protected Object replaceObject(Object obj): This method is used to replace one object with another during serialization.

7. void reset(): The reset() method is used to reset the state of any objects already written to the stream.

8. void write(byte[ ] buf): This method is used to write an array of bytes to the invoking stream.

9. void write(byte[ ] buf, int off, int len): This method is used to write a subarray of bytes, starting at offset.

10. void write(int b): This method is used to write a single byte to the invoking stream. The byte written is the low-order byte of b.


11. void writeBoolean(boolean b): This method is used to write a boolean value to the invoking stream.

12. void writeByte(int b): This method is used to write an 8-bit byte to the invoking stream.

13. void writeBytes(String str): This method is used to write a string as a sequence of bytes representing str to the invoking stream.

14. void writeChar(int ch): This method is used to write a 16-bit char to the invoking stream.

15. void writeChars(String str): This method is used to write a string as a sequence of chars to the invoking stream.


16. protected void writeClassDescriptor(ObjectStreamClass desc): This method is used to write the specified class descriptor to the ObjectOutputStream.

17. void writeDouble(double d): This method is used to write a 64 bit double value to the invoking stream.

18. void writeFields(): The writeFields() method is used to write the buffered fields to the stream.

19. void writeFloat(float f): This method is used to write a 32-bit float value to the invoking stream.

20. void writeInt(int i): It is used to write a 32-bit int value to the invoking stream.


21. void writeLong(long l): The writeLong() method writes a 64-bit long value to the invoking stream.

22. void writeObject(Object obj): The writeObject() method is used to write the specified object to the ObjectOutputStream.

23. protected void writeObjectOverride(Object obj): This method is used by subclasses to override the default writeObject() method.

24. void writeShort(int s): The writeShort() method is used to write a 16-bit short value to the invoking stream

25. protected void writeStreamHeader(): The writeStreamHeader method is used by subclasses to append or prepend their own header to the stream.


26. void writeUnshared(Object obj): This method is used to write an “unshared” object to the ObjectOutputStream.

27. void writeUTF(String str): The writeUTF() method is used to write primitive values representing string str in modified UTF-8 format to the invoking stream.

ObjectOutputStream Example Program


Let’s take an example program where we will write student name, roll no, marks, percentage, and the current data to a file named objfile.txt and then will read these data using ObjectOutputStream and ObjectInputStream classes respectively.

To improve performance, we may add a buffer in the stream. Look at the following source code below.

Program source code 1:

package javaProgram;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

public class TestObjectOutputStream {
public static void main(String[ ] args) throws IOException, ClassNotFoundException 
{
	
// Create an file output stream for file objfile.txt.
     FileOutputStream fos = new FileOutputStream("D:\\objfile.txt");	
  
// Create a buffered output stream and pass the reference fos to its constrcutor.
     BufferedOutputStream bos = new BufferedOutputStream(fos);   

// Create an ObjectOutputStream object and pass reference bos to its constructor.
     ObjectOutputStream oos = new ObjectOutputStream(bos);

// Write a string, int values, double value and object to the file.
       oos.writeUTF("Shubh");
       oos.writeInt(10);
       oos.writeInt(484);
       oos.writeDouble(96.55);
       oos.writeObject(new java.util.Date());	
	
     bos.flush();
     bos.close();
     oos.flush();
     oos.close();
	
// Create an FileInputStream object for the objfile.txt.
     FileInputStream fis = new FileInputStream("D:\\objfile.txt");	

// Craete a buffered input stream and pass the reference fis to its constructor.   
     BufferedInputStream bis = new BufferedInputStream(fis);

// Create an InputStreamObject instance and pass object reference variable fis to its constructor.
     ObjectInputStream ois = new ObjectInputStream(bis);
   
// Read a string, int values, double value and object to the file.
     String name = ois.readUTF();
     int rollNo = ois.readInt();
     int marksObt = ois.readInt();
     double per = ois.readDouble();
     Date date = (Date) ois.readObject();
  
// Display data read on the console.
     System.out.println("Name: " +name);
     System.out.println("Roll no: " +rollNo);
     System.out.println("Total marks obtained: " +marksObt);
     System.out.println("Percentage: " +per+ "%");
     System.out.println("Date: " +date);
   
    bis.close();
    ois.close();
   }
}
Output:
         Name: Shubh
         Roll no: 10
         Total marks obtained: 484
         Percentage: 96.55%
         Date: Sat Aug 07 09:38:36 IST 2021

In this example program, an ObjectOutputStream instance is created to write data into the objfile.txt file. A string, int values, a double value, and an object are written to this file.

To improve performance, we have used a buffer to wrap the FileOutputStream.


Hope that this tutorial has elaborated all the important points related to ObjectOutputStream in Java with example program. I hope that you will have understood the basic concepts of ObjectOutputStream class.

In the next tutorial, we will learn serialization and deserialization in java with example programs.
Thanks for reading!!!