Java.Serialization.How can I create my own serialization protocol?

✅ 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?

ReasonBenefit
Full controlChoose format, compress, encrypt, etc.
Compact storageAvoid unnecessary metadata
Cross-language compatibilityWrite a format that works with Python, C++, etc.
Safe versioningHandle changes across versions easily
Avoid Java serialization quirksNo serialVersionUID, no reflection, no risk of accidental leaks

🧵 TL;DR

StepTool
Save object manuallywriteTo(DataOutput)
Load object manuallyreadFrom(DataInput)
Use custom formatsDataOutputStream, BufferedWriter, binary, JSON, etc.
Add versioningWrite a version byte at the start
Add securityWrap stream with Cipher, GZIP, etc.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.