gpt4 book ai didi

java 将对象序列化为ByteArray

转载 作者:行者123 更新时间:2023-12-02 07:03:20 25 4
gpt4 key购买 nike

大家好!我一直在寻找一些关于 Java 序列化的旧帖子。我想将对象转换为 ByteArray。到目前为止我已经这样做了:

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 的字节值)。

最佳答案

Is it possible to avoid the "junk" values?

是的。写出一个int,而不是一个Object。通过将 int 传递给 writeObject,您可以将其提升(自动装箱)为 Integer,这意味着序列化信息包含 header 信息:它是一个Integer对象,而不是一个int。您的 ByteArrayOutputStream 有 write(int)将一个字节(int 的低 8 位)写入输出流的方法。这些是否已签名纯粹是解释问题,而不是流中的位。

关于java 将对象序列化为ByteArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com