The ObjectInputStream class supports the reading of objects from input streams.
In Core Java, the class that allows you to read objects directly from a stream is ObjectInputStream
. This class is part of the Java I/O (Input/Output) API and is used for deserializing objects from a stream. The ObjectInputStream
reads data written by an ObjectOutputStream
and reconstructs the original objects.
Here’s a basic example of using ObjectInputStream
:
import java.io.*;
public class ObjectInputStreamExample {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("example.ser"))) {
// Reading an object from the stream
MyClass obj = (MyClass) ois.readObject();
// Now, you can work with the deserialized object (obj)
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, example.ser
is a serialized file containing objects of the class MyClass
, and ObjectInputStream
is used to read and deserialize these objects from the file.