ObjectOutputStream Class in Java

Introduction

The ObjectOutputStream class in Java is part of the java.io package and is used to serialize objects to an output stream. 

Serialization is the process of converting an object's state into a byte stream so that the byte stream can be reverted back into a copy of the object. 

This class is essential for writing objects and primitive data types to an output stream, allowing objects to be saved to a file, transmitted over a network, or stored in a database.

Table of Contents

  1. Creating an ObjectOutputStream
  2. Writing Objects with ObjectOutputStream
  3. Closing the Stream
  4. Complete Example
  5. Conclusion

Creating an ObjectOutputStream

To create an ObjectOutputStream, you need to wrap it around another output stream, such as a FileOutputStream. This allows you to write serialized objects to a file or another output destination.

Example

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

public class ObjectOutputStreamExample {
    public static void main(String[] args) {
        try {
            // Creating ObjectOutputStream using FileOutputStream
            FileOutputStream fos = new FileOutputStream("example.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, ObjectOutputStream is created using a FileOutputStream to write to a file named example.ser.

Writing Objects with ObjectOutputStream

The ObjectOutputStream class provides methods to write objects and primitive data types to the output stream:

  • void writeObject(Object obj): Writes an object to the output stream.
  • void writeBoolean(boolean v): Writes a boolean value.
  • void writeByte(int v): Writes an 8-bit byte.
  • void writeChar(int v): Writes a 16-bit character.
  • void writeDouble(double v): Writes a 64-bit double.
  • void writeFloat(float v): Writes a 32-bit float.
  • void writeInt(int v): Writes a 32-bit integer.
  • void writeLong(long v): Writes a 64-bit long.
  • void writeShort(int v): Writes a 16-bit short.
  • void writeUTF(String str): Writes a string in UTF-8 format.

Example

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

public class ObjectOutputStreamWriteExample {
    public static void main(String[] args) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("example.ser"))) {
            oos.writeInt(12345);
            oos.writeDouble(123.45);
            oos.writeBoolean(true);
            oos.writeUTF("Hello, World!");

            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, ObjectOutputStream writes an integer, a double, a boolean, and a UTF-8 encoded string to a file named example.ser.

Closing the Stream

It is important to close the ObjectOutputStream after completing the I/O operations to release the system resources associated with the stream. This can be done using the close() method.

Example

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

public class ObjectOutputStreamCloseExample {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("example.ser"));
            oos.writeInt(12345);
            oos.writeDouble(123.45);
            oos.writeBoolean(true);
            oos.writeUTF("Hello, World!");

            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

In the example above, the ObjectOutputStream is closed in the finally block to ensure that it is closed even if an exception occurs.

Alternatively, you can use the try-with-resources statement, which ensures that the stream is closed automatically.

Example

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

public class ObjectOutputStreamTryWithResourcesExample {
    public static void main(String[] args) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("example.ser"))) {
            oos.writeInt(12345);
            oos.writeDouble(123.45);
            oos.writeBoolean(true);
            oos.writeUTF("Hello, World!");

            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, the try-with-resources statement is used to automatically close the ObjectOutputStream.

Complete Example

Here is a complete example demonstrating the creation, writing, and closing of an ObjectOutputStream.

ObjectOutputStreamExample.java

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

public class ObjectOutputStreamExample {
    public static void main(String[] args) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("example.ser"))) {
            oos.writeInt(12345);
            oos.writeDouble(123.45);
            oos.writeBoolean(true);
            oos.writeUTF("Hello, World!");

            System.out.println("Data written and flushed to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, an ObjectOutputStream is created, data is written to a file, the stream is flushed, and the stream is automatically closed using the try-with-resources statement.

Conclusion

The ObjectOutputStream class in Java is used for serializing objects and writing primitive data types to an output stream. By understanding how to create, write, and close an ObjectOutputStream, you can effectively handle serialization in your Java applications. Remember to always close the stream after use to ensure that system resources are properly released.

Comments