Java.Serialization.CompressionExample

import java.io.*;
import java.util.zip.*;

public class CompressedPerson implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private transient String bio; // a long text we want to compress

    public CompressedPerson(String name, String bio) {
        this.name = name;
        this.bio = bio;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject(); // serialize 'name'

        // Compress 'bio' and write it
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(byteOut);
        gzip.write(bio.getBytes("UTF-8"));
        gzip.close();
        byte[] compressed = byteOut.toByteArray();

        out.writeInt(compressed.length); // write length first
        out.write(compressed);           // write compressed bytes
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject(); // read 'name'

        // Read and decompress 'bio'
        int length = in.readInt();
        byte[] compressed = new byte[length];
        in.readFully(compressed);

        ByteArrayInputStream byteIn = new ByteArrayInputStream(compressed);
        GZIPInputStream gzip = new GZIPInputStream(byteIn);
        InputStreamReader reader = new InputStreamReader(gzip, "UTF-8");
        BufferedReader br = new BufferedReader(reader);

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        this.bio = sb.toString().trim(); // restore 'bio'
    }

    public String getName() {
        return name;
    }

    public String getBio() {
        return bio;
    }
}

✅ Usage

CompressedPerson person = new CompressedPerson("Stanley", "This is a long bio...");

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("compressed.ser"))) {
    out.writeObject(person);
}

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("compressed.ser"))) {
    CompressedPerson restored = (CompressedPerson) in.readObject();
    System.out.println("Name: " + restored.getName());
    System.out.println("Bio: " + restored.getBio());
}

🧠 What Happens

StepWhat Java Does
writeObject()Compresses the bio field to a byte array and writes it
readObject()Reads the compressed byte array and decompresses it back into bio
transientSkips the field from default serialization so we can handle it manually

🧵 TL;DR

  • This approach is perfect when you have large strings or blobs of text.
  • It saves space in .ser files.
  • You can do the same for binary fields (images, docs, etc).
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.