Java I/O Streams: ObjectInputStream and ObjectOutputStream
Java provides ObjectInputStream
and ObjectOutputStream
classes for serialization and deserialization of objects. These classes are part of the java.io
package and are used when you want to save the state of an object or send it over a network.
1. What Are ObjectInputStream and ObjectOutputStream?#
- ObjectOutputStream: Used to serialize Java objects into a stream of bytes and write them to an OutputStream (like a file).
- ObjectInputStream: Used to deserialize the stream of bytes into a Java object from an InputStream.
These streams are commonly used when storing objects in files or transmitting them over the network.
2. ObjectOutputStream Methods (With Examples)#
● void writeObject(Object obj)
#
Serializes the given object and writes it to the output stream.
Example:#
Output:#
(File student.ser
contains serialized byte data of the Student
object)
Something like this :
���sr�Student���I��/G�I�idL�namet�Ljava/lang/String;xp���t�John
3. ObjectInputStream Methods (With Examples)#
● Object readObject()
#
Reads an object from the input stream and deserializes it.
Example:#
Output:#
4. When to Use ObjectInputStream and ObjectOutputStream?#
- Use when you need to save and restore the complete state of an object.
- Use for sending objects over sockets (network communication).
- Makes storing and retrieving complex data structures (like maps, lists of objects) very convenient.
Important Note:
- The class whose objects are to be serialized must implement the
Serializable
interface. - All non-serializable fields should be marked
transient
if they must be excluded from serialization.
Conclusion#
In this blog, we explored how to use ObjectInputStream and ObjectOutputStream for object serialization and deserialization. These classes are especially useful when persisting the state of objects or transmitting them over a network.
In the next blog, we will dive into BufferedInputStream and BufferedOutputStream, which help improve performance by reducing disk access.