java ObjectOutputStream 中的开销?

hin*_*gen 5 java serialization bytearray objectoutputstream

我对 ObjectOutputStream 的行为感到困惑。写入数据时似乎有 9 个字节的开销。考虑下面的代码:

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();
Run Code Online (Sandbox Code Playgroud)

数组的长度总是 781,而我希望它是 (1+96+96)*4 = 772 字节。我似乎无法找到 9 个字节的去向。

谢谢!

--edit: 添加 if(oos!=null) { ... } 以防止 NPE

Pio*_*zmo 3

对象输出流用于序列化对象。您不应该对数据的存储方式做出任何假设。

如果您只想存储原始数据,请使用DataOutputStream