简体   繁体   English

从 ObjectOutputStream 取回 Object

[英]Getting Object back from an ObjectOutputStream

I have created an ObjectOutputStream我创建了一个 ObjectOutputStream

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

but how do I now convert this back into an Object , or even a ByteArray ?但是我现在如何将其转换回Object ,甚至是ByteArray

I've tried getting an ObjectInputStream like this我试过像这样得到一个 ObjectInputStream

ByteArrayOutputStream outputStream = (ByteArrayOutputStream) myProcess.getOutputStream();

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

however I get a compile error saying it can't cast the ObjectOutputStream to a ByteArrayOutputStream ;但是我收到一个编译错误,说它不能将ObjectOutputStream转换为ByteArrayOutputStream yet there seem to be no methods on the ObjectOutputStream to get the data back?但是ObjectOutputStream上似乎没有方法可以取回数据?

Here how you do it在这里你怎么做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM