【问题标题】:How to (de)serialize correctly to a byte-array using a ObjectOutputStream & ObjectInputStream?如何使用 ObjectOutputStream 和 ObjectInputStream 正确(反)序列化为字节数组?
【发布时间】:2017-07-26 11:11:47
【问题描述】:

我知道 ObjectOutputStream/ObjectInputStream 使用标头,这并不是一个真正合适的用例。但无论如何,我需要使用接口 DataInput 和 DataOutput 将一些数据包装到其中。

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        byte[] array = serialize("test");
        String deserialized = deserialize(array);

        System.out.println(deserialized);
    }

    private static byte[] serialize(String test) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

            objectOutputStream.writeUTF(test);

            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return byteArrayOutputStream.toByteArray();
    }

    private static String deserialize(byte[] array) {
        String temp = null;

        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(array));

            temp = objectInputStream.readUTF();

            objectInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return temp;
    }
}

我真的不知道如何让它发挥作用。我是对的,问题出在当前的那些标头上吗?

【问题讨论】:

  • 什么不起作用?你有异常或错误的结果?您也可以在帖子中提供minimal working example
  • 你应该在你的问题中发布你的代码,因为外部资源不可靠,将来有人可能会遇到同样的问题,但由于链接断开而无法理解你的问题。这次我是为你做的,但以后请你自己做。

标签: java arrays stream byte


【解决方案1】:

您应该在关闭byteArrayOutputStream之前致电objectOutputStream.flush();

ObjectOutputStream 有其内部缓冲区,因此您的字节数组中只有字符串的开头。

【讨论】:

  • 你应该刷新objectOutputStream而不是byteArrayOutputStream。冲洗byteArrayOutputStream 没用。它总是直接写入缓冲区。
  • @Tobseb ,在你的代码中你应该做objectOutputStream.writeUTF(test); objectOutputStream.flush(); byteArrayOutputStream.close();
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 2011-09-29
  • 2014-10-18
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
相关资源
最近更新 更多