✅ Example: Manual Serialization Protocol
🔹 Step 1: Define a class with custom writeTo()
and readFrom()
methods
import java.io.*;
public class User {
private String username;
private int age;
public User(String username, int age) {
this.username = username;
this.age = age;
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeUTF(username);
out.writeInt(age);
}
public static User readFrom(DataInputStream in) throws IOException {
String username = in.readUTF();
int age = in.readInt();
return new User(username, age);
}
@Override
public String toString() {
return username + " (" + age + ")";
}
}
🔹 Step 2: Save the object manually
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("user.bin"))) {
new User("Stanley", 33).writeTo(out);
}
🔹 Step 3: Load the object manually
try (DataInputStream in = new DataInputStream(new FileInputStream("user.bin"))) {
User loaded = User.readFrom(in);
System.out.println("Restored: " + loaded); // Restored: Stanley (33)
}
🔐 Bonus: Add encryption, compression, versioning
➕ Versioning
Add a version byte at the start:
out.writeByte(1); // version 1
Then during read:
int version = in.readByte();
if (version == 1) {
// read fields...
}
➕ Encryption
Wrap your stream with a cipher stream:
CipherOutputStream cos = new CipherOutputStream(fos, myCipher);
➕ Compression
Wrap with GZIPOutputStream
or DeflaterOutputStream
.
🧠 Why Create Your Own Protocol?
Reason | Benefit |
---|---|
Full control | Choose format, compress, encrypt, etc. |
Compact storage | Avoid unnecessary metadata |
Cross-language compatibility | Write a format that works with Python, C++, etc. |
Safe versioning | Handle changes across versions easily |
Avoid Java serialization quirks | No serialVersionUID , no reflection, no risk of accidental leaks |
🧵 TL;DR
Step | Tool |
---|---|
Save object manually | writeTo(DataOutput) |
Load object manually | readFrom(DataInput) |
Use custom formats | DataOutputStream , BufferedWriter , binary, JSON, etc. |
Add versioning | Write a version byte at the start |
Add security | Wrap stream with Cipher , GZIP , etc. |