CKTIS / Java
ObjectInputStream — deserializing objects
ObjectInputStream reconstructs objects from Java's binary serialization stream. Learn readObject(), exception handling, and closure through close(), while recognizing that deserializing untrusted data is dangerous.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public ObjectInputStream(InputStream in) throws IOException
public final Object readObject() throws IOException, ClassNotFoundException
public void close() throws IOExceptionObjectInputStream in java.io reads data written by ObjectOutputStream, not arbitrary text or JSON. Its constructor takes an InputStream and checks the serialization header; it can block until that header arrives. This entry targets Java SE 21; repository and production runtimes are not attested.
ObjectInputStream.readObject() reconstructs an object and the objects it references, preserving shared references. It returns Object, including null, so the expected type requires a check or cast. Read values in the same order and with types matching the writes; primitive data uses methods such as readInt(). The method declares IOException and ClassNotFoundException; an incompatible class can cause InvalidClassException.
ObjectInputStream.close() closes the stream and releases associated resources; it can throw IOException. Use try-with-resources to invoke close() even after an exception. The example writes a local String into memory, then reads it and prints Hello, Java!.
Avoid deserializing untrusted data: class methods can execute during reconstruction. Casting after readObject() is not a security measure. When deserialization is necessary, configure an ObjectInputFilter before reading to restrict allowed classes and graph size; filtering does not replace data validation.
Examples
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject("Hello, Java!");
}
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()))) {
String message = (String) in.readObject();
System.out.println(message);
}
}
}
Result
Hello, Java!
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.