How can I determine the byte length of an object that I serialize to a stream?
Created May 4, 2012
Tim Rohaly
There are a couple of things you can do. First, you can pipe the ObjectOutputStream into a ByteArrayOutputStream, then examine the length of the byte array:
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = ObjectOutputStream(baos); out.writeObject(new MyObject()); out.flush(); // // Subtract 4 bytes from the length, because the serialization // magic number (2 bytes) and version number (2 bytes) are // both written to the stream before the object // int objectsize = baos.toByteArray().length - 4; System.out.println("MyObject occupies " + objectsize + " bytes when serialized");
Or, if you want to stream to a destination other than a byte array, you can write a subclass of DataOutputStream which allows you to access the protected variable written. This subclass can be used to monitor the data sent through the stream to any destination source:
import java.io.*; public class ByteCounterOutputStream extends DataOutputStream { public ByteCounterOutputStream(OutputStream out) { super(out); } public int bytesWrittenSoFar() { return written; } }To use this to write to a file and count the size of the objects written on-the-fly, you would do the following:
FileOutputStream file = new FileOutputStream("junk"); ByteCounterOutputStream bcos = new ByteCounterOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(bcos); int start = bcos.bytesWrittenSoFar(); out.writeObject(new MyObject()); out.flush(); int objectsize = bcos.bytesWrittenSoFar() - start; System.out.println("MyObject occupies " + objectsize + " bytes when serialized");