【问题标题】:Getting Object back from an ObjectOutputStream从 ObjectOutputStream 中取回对象
【发布时间】:2019-04-26 10:05:11
【问题描述】:

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

【问题讨论】:

    标签: java stream outputstream bytearrayoutputstream


    【解决方案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();
    

    【讨论】:

    • 啊,是的,在 ByteArrayOutputStream 而不是 ObjectOutputStream 上操作有所不同
    猜你喜欢
    • 2018-03-17
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 2016-08-01
    相关资源
    最近更新 更多