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.
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:
read()– Reads a single byte.readBoolean()– Reads a boolean value.readChar()– Reads a character.readInt()– Reads an integer.readObject()– Reconstructs an object from the stream.
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:
- Use
ObjectOutputStreamto write objects. - Use
ObjectInputStreamto read them back. - Only objects that implement
Serializablecan be serialized.
Additional ObjectInputStream Methods
| Method | Description |
|---|---|
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
- Understanding Java’s final Keyword: Variables, Methods, and Classes
- Java instanceof Operator: A Comprehensive Guide
- Mastering Java Inheritance: Concepts, Types, and Practical Examples
- Understanding Java Nested Static Classes: Usage, Differences, and Examples
- Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
- Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
- Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
- Mastering Java Reader Class: Subclasses, Methods, and Practical Example
- Mastering Java Generics – Building Reusable, Type‑Safe Code
- Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion