【发布时间】:2013-04-29 01:30:32
【问题描述】:
大家好!我一直在寻找一些关于 Java 中的序列化的旧帖子。 我想将一个对象转换为一个字节数组。到目前为止,我已经这样做了:
public class test
{
public static void main(String[] args) throws IOException
{
// 00111111 00111111 00111111 11110000 - in bytes: 63, 63, 63, 240
int x = 1061109744;
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(x);
bytes = bos.toByteArray();
}
finally
{
out.close();
bos.close();
}
System.out.println("Lenght: " + bytes.length);
for(int i=0; i < bytes.length; i++)
{
System.out.println(bytes[i]);
}
}
}
显然它工作得很好,但它在ByteArray 中引入了很多“垃圾”。我真正感兴趣的值是与我的“int x = 1061109744;”相对应的最后 4 个字节。
为什么会这样?
是否可以避免“垃圾”值?
是否有可能超过“签名”值? (我必须写大于 128 的字节值)。
【问题讨论】:
标签: java object serialization signed