gpt4 book ai didi

java - ObjectOutputStream.toByteArray 返回垃圾

转载 作者:行者123 更新时间:2023-11-30 04:41:03 27 4
gpt4 key购买 nike

我需要从发送到输出流的所有内容中获取字节数组。但我却得到了 4 个字节的垃圾。为什么?

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.write(new byte[]{1,2,3,4,5,6,7,8,9});
byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original)); // why not [1,2,3,4,5,6,7,8,9]?

最佳答案

您的代码中有几个缺陷。首先,您应该使用writeObject():

objectOutputStream.writeObject(new byte[]{1,2,3,4,5,6,7,8,9});

那么你应该使用对称的ObjectInputStream来读取:

final ObjectInputStream objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(
byteArrayOutputStream.toByteArray()
)
);
byte[] original = (byte[]) objectInputStream.readObject();

但是如果您已经有一个 byte[],则使用 Java 序列化将其转换为字节数组(它已经是字节数组了!)是没有意义的,只需编写并直接阅读:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9});
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
byteArrayOutputStream.toByteArray()
);
final byte[] original = new byte[9];
byteArrayInputStream.read(original);
System.out.println(Arrays.toString(original));

关于java - ObjectOutputStream.toByteArray 返回垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12299889/

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