从ObjectOutputStream取回对象

时间:2019-04-26 10:05:12

标签: java stream outputstream bytearrayoutputstream

我创建了一个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上似乎没有方法可以取回数据?

1 个答案:

答案 0 :(得分:1)

这是怎么做

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();