java 从ObjectOutputStream取回对象

yeotifhr  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(103)

我创建了一个ObjectOutputStream

ObjectOutputStream stream = new ObjectOutputStream(new ByteArrayOutputStream());
stream.writeObject(myObject);

但现在如何将其转换回Object,甚至是ByteArray呢?
我试过得到这样的ObjectInputStream

ByteArrayOutputStream outputStream = (ByteArrayOutputStream) myProcess.getOutputStream();
            
final ObjectInputStream objectInputStream = new ObjectInputStream(
    new ByteArrayInputStream(outputStream.toByteArray()));

但是我收到一个编译错误,说它不能将ObjectOutputStream转换为ByteArrayOutputStream;然而在ObjectOutputStream上似乎没有方法来取回数据?

sxpgvts3

sxpgvts31#

这就是你的做法

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(baos);
stream.writeObject(myObject);

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream inputStream = new ObjectInputStream(bais);
Object o = inputStream.readObject();

相关问题