gpt4 book ai didi

java - 写入 ObjectOutputStream 并返回垃圾

转载 作者:行者123 更新时间:2023-11-29 10:18:13 27 4
gpt4 key购买 nike

我将一些对象放入流中,然后从中取出字节数组,然后读回所有内容。前两条数据完好无损,然后我得到零,然后是 EOF 异常。为什么?

try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject("abcdef");
objectOutputStream.writeInt(1);
objectOutputStream.writeObject(new byte[]{1,2,3,4,5,6,7,8});
objectOutputStream.writeInt(2);
objectOutputStream.writeObject(new byte[]{11,12,13,14,15,16,17,18});
objectOutputStream.close();


byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original));

byte[] b=new byte[8];
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(original));
String s= (String) objectInputStream.readObject(); // works fine
objectInputStream.readInt(); // works fine

objectInputStream.read(b); // why it reads zeroes instead of [1,2,3,4,5,6,7,8]?
System.out.println(Arrays.toString(b));
int length = objectInputStream.readInt(); // EOF unexpectedly reached, why?
objectInputStream.read(b);
}
catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

异常(exception):

java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:375)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2775)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:949)

最佳答案

我怀疑第一个问题是您需要close() 您的objectOutputStream。查看ObjectOutputStream documentation例如。

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

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