Implementing writeExternal: Writing Custom Binary Format
You'll learn how to take complete control of object serialization by implementing the writeExternal method to write data in your own custom binary format.
What Is writeExternal?
When you implement the Externalizable interface, you must define the writeExternal method. Unlike the optional writeObject method from Serializable, writeExternal gives you total responsibility for writing your object's state to the output stream. No automatic serialization happens—you specify exactly which fields to write and in what format.
Think of it like packing a suitcase yourself versus having someone else pack it for you. With Serializable, Java automatically packs everything (except transient fields). With Externalizable, you choose every item and how to arrange it.
The Method Signature
public void writeExternal(ObjectOutput out) throws IOException
The ObjectOutput parameter provides methods like writeInt(), writeUTF(), writeBoolean(), writeObject(), and more—giving you fine-grained control over the binary format.
Writing Your Custom Format
public class Employee implements Externalizable {
private String name;
private int id;
private transient String tempData; // You control if this gets written
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name); // Write String in UTF format
out.writeInt(id); // Write int as 4 bytes
out.writeBoolean(true); // Write a flag for future use
// Note: tempData is NOT written—we decide
}
// Constructor and readExternal omitted for focus
}
You decide the order, format, and which fields to serialize. This efficiency is why Externalizable can be faster and produce smaller output than default serialization.
Key Takeaway: The writeExternal method lets you define a precise, custom binary format by explicitly writing each field using ObjectOutput methods, giving you complete control over serialization.