我是序列化的新手。
我试着编写简单的代码。 我得到了奇怪的结果。我不明白。
我有这段代码:
package easybudda.fakesizeof;
import java.io.*;
public class FakeSizeOf {
public static void main(String[] args) throws IOException {
Object[] arr = { new Boolean(true), new Character('ы'), new Integer(13), new Long(69L), new Double(3.14) };
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ObjectOutputStream objOutStream = new ObjectOutputStream(outStream);
for ( Object obj : arr ) {
outStream.reset();
objOutStream.writeObject(obj);
objOutStream.flush();
System.out.println(obj.getClass().getSimpleName() + ": " + outStream.size());
}
System.out.println("\nUsing predefined methods:");
outStream.reset();
objOutStream.write(13);
objOutStream.flush();
System.out.println("write with int as data: " + outStream.size());
outStream.reset();
objOutStream.writeBoolean(false);
objOutStream.flush();
System.out.println("writeBoolean: " + outStream.size());
outStream.reset();
objOutStream.writeByte(1);
objOutStream.flush();
System.out.println("writeByte: " + outStream.size());
outStream.reset();
objOutStream.writeChar('ы');
objOutStream.flush();
System.out.println("writeChar: " + outStream.size());
outStream.reset();
objOutStream.writeDouble(3.14);
objOutStream.flush();
System.out.println("writeDouble: " + outStream.size());
outStream.reset();
objOutStream.writeInt(13);
objOutStream.flush();
System.out.println("writeInt: " + outStream.size());
outStream.reset();
objOutStream.writeLong(69L);
objOutStream.flush();
System.out.println("writeLong: " + outStream.size());
}
}
输出:
Boolean: 43
Character: 46
Integer: 77
Long: 51
Double: 53
Using predefined methods:
write with int as data: 3
writeBoolean: 3
writeByte: 3
writeChar: 4
writeDouble: 10
writeInt: 6
writeLong: 10
有人可以为我开出这些结果吗?
1.例如int - 4字节(6输出) - 为什么?
2.为什么阵列如此巨大?
答案 0 :(得分:0)
ObjectOutputStream
会为其编写的所有内容添加类型信息。请参阅Object Serialization Specification,协议章节:
类所写的所有原始数据都被缓冲并包装在块数据记录中,无论数据是在
writeObject
方法中写入流还是从writeObject
外部直接写入流中。方法
例如,writeInt(13)
写[119,4,0,0,0,13],这意味着
TC_BLOCKDATA,size=4 bytes,0,0,0,13.