Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead in java ObjectOutputStream?

I am puzzled by the behavior of ObjectOutputStream. It seems like it has an overhead of 9 bytes when writing data. Consider the code below:

float[] speeds = new float[96];
float[] flows = new float[96];

//.. do some stuff here to fill the arrays with data

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos=null;
try {
    oos = new ObjectOutputStream(baos);
    oos.writeInt(speeds.length);
    for(int i=0;i<speeds.length;i++) {
        oos.writeFloat(speeds[i]);
    }
    for(int i=0;i<flows.length;i++) {
        oos.writeFloat(flows[i]);
    }
    oos.flush();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if(oos!=null) {
            oos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

byte[] array = baos.toByteArray();

The length of the array is always 781, while I would expect it to be (1+96+96)*4 = 772 bytes. I can't seem to find where the 9 bytes go.

Thanks!

--edit: added if(oos!=null) { ... } to prevent NPE

like image 577
hinsbergen Avatar asked Feb 27 '12 13:02

hinsbergen


1 Answers

ObjectOutputStream is used to serialize objects. You shouldn't make any assumptions how the data is stored.

If you want to store just the raw data use DataOutputStream instead.

like image 166
Piotr Praszmo Avatar answered Sep 26 '22 01:09

Piotr Praszmo