Java I/O Object Streams

Object streams in Java are used to serialize and deserialize objects, allowing for the conversion of objects into a byte stream and vice versa. This is useful for persisting objects to a file or sending them over a network. The primary classes for object streams are ObjectInputStream and ObjectOutputStream.

Table of Contents

  1. Introduction
  2. Object Stream Classes
    • ObjectInputStream
    • ObjectOutputStream
  3. Examples
    • Writing Objects to a File
    • Reading Objects from a File
  4. SerialVersionUID
  5. Conclusion

Introduction

Serialization in Java is the process of converting an object into a byte stream, which can then be saved to a file or sent over a network. Deserialization is the reverse process, where the byte stream is converted back into an object. Object streams handle these processes, making it possible to easily store and retrieve objects.

Object Stream Classes

ObjectInputStream

The ObjectInputStream class deserializes objects and primitive data that were previously written using an ObjectOutputStream.

Common Methods:

  • Object readObject()
  • boolean readBoolean()
  • byte readByte()
  • char readChar()
  • double readDouble()
  • float readFloat()
  • int readInt()
  • long readLong()
  • short readShort()

ObjectOutputStream

The ObjectOutputStream class serializes objects and primitive data and writes them to an OutputStream.

Common Methods:

  • void writeObject(Object obj)
  • void writeBoolean(boolean v)
  • void writeByte(int v)
  • void writeChar(int v)
  • void writeDouble(double v)
  • void writeFloat(float v)
  • void writeInt(int v)
  • void writeLong(long v)
  • void writeShort(int v)

Examples

Writing Objects to a File

The following example demonstrates how to serialize and write an object to a file using ObjectOutputStream.

Example

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

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class ObjectOutputStreamExample {
    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • Person class implements Serializable, allowing instances to be serialized.
  • ObjectOutputStream is used to write the Person object to a file named person.dat.

Reading Objects from a File

The following example demonstrates how to read and deserialize an object from a file using ObjectInputStream.

Example

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamExample {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
            Person person = (Person) ois.readObject();
            System.out.println("Read object: " + person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • ObjectInputStream is used to read the Person object from a file named person.dat.
  • The readObject() method reads the object from the file and returns it as an Object, which is then cast to Person.

Copying Objects Using Object Streams

The following example demonstrates how to copy an object from one file to another using ObjectInputStream and ObjectOutputStream.

Example

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

public class ObjectStreamCopyExample {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"));
             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person_copy.dat"))) {
            Person person = (Person) ois.readObject();
            oos.writeObject(person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • ObjectInputStream reads the Person object from person.dat.
  • ObjectOutputStream writes the Person object to person_copy.dat, effectively copying the object.

SerialVersionUID

When a class implements Serializable, it is recommended to declare a serialVersionUID. This ID is used during deserialization to verify that the sender and receiver of a serialized object maintain compatibility regarding the serialized class.

Example

private static final long serialVersionUID = 1L;

If the serialVersionUID is not explicitly declared, Java will generate one automatically based on various aspects of the class, which can lead to unexpected InvalidClassException during deserialization if the class structure changes.

Conclusion

Object streams in Java provide a way to serialize and deserialize objects, allowing for the conversion of objects into a byte stream and vice versa. This functionality is essential for persisting objects to a file or sending them over a network. By understanding how to use ObjectInputStream and ObjectOutputStream, you can efficiently manage and process objects in your Java applications. The examples provided demonstrate basic usage, including writing objects to a file, reading objects from a file, and copying objects using object streams. Additionally, the importance of serialVersionUID in maintaining serialization compatibility is highlighted.

Comments