Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples

Java ObjectOutputStream Class

Explore the Java ObjectOutputStream API, its core methods, and step‑by‑step examples that demonstrate how to serialize objects to files and read them back.

The ObjectOutputStream class from the java.io package lets you write Java objects so they can be read later by ObjectInputStream. It extends OutputStream and is the backbone of Java’s built‑in serialization mechanism.

Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples


How ObjectOutputStream Works

When you write an object to an ObjectOutputStream, the framework encodes the object’s class name, field values, and type information into a binary format—a process known as serialization. The resulting byte stream can be stored in a file, transmitted over a network, or even embedded in memory.

Important: Only objects that implement java.io.Serializable can be serialized. This interface acts as a marker to inform the runtime that an object is safe to be persisted or transmitted.


Creating an ObjectOutputStream

Begin by importing the class:

import java.io.ObjectOutputStream;
Then, link it to a FileOutputStream or any other underlying OutputStream:

// Write to a file named "data.bin"
FileOutputStream fileStream = new FileOutputStream("data.bin");
ObjectOutputStream objStream = new ObjectOutputStream(fileStream);

Here, objStream is now ready to serialize objects into fileStream.


Key Methods of ObjectOutputStream

The class inherits a suite of methods from OutputStream and adds specialized ones for object handling:


Example 1: Serializing Primitive and String Data

Below is a complete snippet that writes an int and a String to a file, then reads them back using ObjectInputStream:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        int data1 = 5;
        String data2 = "This is programiz";

        try {
            // Write objects
            FileOutputStream fos = new FileOutputStream("file.bin");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeInt(data1);
            oos.writeObject(data2);
            oos.close();

            // Read objects
            FileInputStream fis = new FileInputStream("file.bin");
            ObjectInputStream ois = new ObjectInputStream(fis);
            System.out.println("Integer data :" + ois.readInt());
            System.out.println("String data :" + ois.readObject());
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Integer data :5
String data :This is programiz

Example 2: Serializing a Custom Object

To serialize a user‑defined class, simply implement Serializable:

import java.io.*;

class Dog implements Serializable {
    String name;
    String breed;

    Dog(String name, String breed) {
        this.name = name;
        this.breed = breed;
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog1 = new Dog("Tyson", "Labrador");

        try {
            // Write the object
            FileOutputStream fos = new FileOutputStream("dog.bin");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(dog1);
            oos.close();

            // Read the object
            FileInputStream fis = new FileInputStream("dog.bin");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Dog newDog = (Dog) ois.readObject();
            System.out.println("Dog Name: " + newDog.name);
            System.out.println("Dog Breed: " + newDog.breed);
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Dog Name: Tyson
Dog Breed: Labrador

The Dog class must implement Serializable because ObjectOutputStream can only write serializable objects.


Additional ObjectOutputStream Operations

Method Description
flush() Flushes any buffered output bytes to the underlying stream.
drain() Flushes buffered data (available in Java 9+).
close() Closes the stream and releases any system resources.

For a deeper dive, consult the official Java documentation.

Java

  1. Understanding Java’s final Keyword: Variables, Methods, and Classes
  2. Java instanceof Operator: A Comprehensive Guide
  3. Mastering Java Inheritance: Concepts, Types, and Practical Examples
  4. Understanding Java Nested Static Classes: Usage, Differences, and Examples
  5. Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
  6. Mastering Java’s ObjectInputStream: A Comprehensive Guide
  7. Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
  8. Mastering Java Reader Class: Subclasses, Methods, and Practical Example
  9. Mastering Java Generics – Building Reusable, Type‑Safe Code
  10. Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion