Course contentsShow
← Java
Lesson 2151 of 2,87042. SerializationFree lesson

Implementing readExternal: Reading Custom Binary Format

Understand how readExternal reconstructs objects by reading data in the same order it was written.

Implementing readExternal: Reading Custom Binary Format

You'll learn how to reconstruct objects from custom binary data using readExternal, respecting the exact order data was written.

The Mirror Image of Serialization

When you implemented writeExternal, you took control of how your object's data was written to a binary stream. Now readExternal is the flip side: you must read that data back in exactly the same order and using the same data types. Think of it like assembling furniture—if the instructions say "attach leg A, then leg B," you can't reverse the order or you'll end up with mismatched pieces.

How readExternal Works

The readExternal method receives an ObjectInput parameter (which extends DataInput), giving you access to methods like readInt(), readUTF(), readBoolean(), etc. Your job is to:

  1. Read each value in the exact sequence you wrote them
  2. Use the matching read method for each write method
  3. Assign the values to your object's fields

If your writeExternal wrote an int, then a String, then a boolean, your readExternal must read an int, then a String, then a boolean—no exceptions. Mix up the order or types, and you'll get corrupted data or runtime exceptions.

The Critical Contract

The order and type symmetry is non-negotiable. If you wrote writeInt(age); writeUTF(name);, you must read age = readInt(); name = readUTF();. This is your responsibility—Java won't enforce it for you, but breaking this contract results in gibberish data or crashes.

Key Takeaway: readExternal reconstructs objects by reading data in the exact same order and with matching types as writeExternal wrote them—maintaining this symmetry is your responsibility.