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

Mastering Java’s ObjectInputStream: A Comprehensive Guide

Java ObjectInputStream Class

Explore how to read serialized objects in Java with ObjectInputStream, complete with step‑by‑step examples and practical tips.

The ObjectInputStream class in the java.io package allows you to deserialize objects that were previously written by ObjectOutputStream. It extends the abstract InputStream class.

Mastering Java’s ObjectInputStream: A Comprehensive Guide

Before diving into ObjectInputStream, ensure you’re familiar with the ObjectOutputStream class, as it handles the serialization process.


How ObjectInputStream Works

Serialization transforms Java objects into a byte stream that can be stored or transmitted. Deserialization—the reverse process—is handled by ObjectInputStream, which reads the byte stream and reconstructs the original objects.


Creating an ObjectInputStream

To create an ObjectInputStream, first import the class and then link it to a source, typically a FileInputStream:

// Link to a file
FileInputStream fileStream = new FileInputStream("example.dat");

// Wrap it in an ObjectInputStream
ObjectInputStream objStream = new ObjectInputStream(fileStream);

Once instantiated, objStream can read any serialized objects from the file.


Key Methods of ObjectInputStream

Below are the most frequently used methods:


Example 1: Basic Deserialization

Below is a minimal example that writes an integer and a string to a file, then reads them back.

import java.io.*;

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

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

            // Read data
            FileInputStream fis = new FileInputStream("file.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            System.out.println("Integer data :" + ois.readInt());
            System.out.println("String data :" + ois.readObject());

            oos.close();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Integer data :5
String data :This is programiz

Example 2: Deserializing a Custom Object

Serialize and deserialize a simple Dog object. Remember, the class must implement Serializable for this to work.

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 dog = new Dog("Tyson", "Labrador");

        try {
            // Serialize
            FileOutputStream fos = new FileOutputStream("file.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(dog);

            // Deserialize
            FileInputStream fis = new FileInputStream("file.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Dog newDog = (Dog) ois.readObject();

            System.out.println("Dog Name: " + newDog.name);
            System.out.println("Dog Breed: " + newDog.breed);

            oos.close();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Dog Name: Tyson
Dog Breed: Labrador

Key takeaways:


Additional ObjectInputStream Methods

MethodDescription
available()Returns the number of bytes that can be read without blocking.
mark()Marks the current position in the stream.
reset()Resets the stream to the most recent mark.
skipBytes(int n)Skips n bytes.
close()Closes the stream and releases resources.

For deeper insight, visit 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 ObjectOutputStream: Serialization, Methods, and Practical Examples
  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