java - 无效的流 header : EFBFBDEF when converting object from byte string

标签 java arrays

我正在尝试将 ArrayList 对象转换为字节字符串,以便它可以通过套接字发送。当我运行此代码时,它会正确转换为字符串,但当我尝试将其转换回来时,出现异常“java.io.StreamCorruptedException:无效的流 header :EFBFBDEF”。我在这里看到的其他答案并没有真正帮助,因为我使用的是匹配的 ObjectOutputStream 和 ObjectInputStream。很抱歉,如果有一个简单的修复方法,因为我是使用流对象的新手。

try {
        ArrayList<String> text = new ArrayList<>();
        text.add("Hello World!");
        String byteString = Utils.StringUtils.convertToByteString(text);
        ArrayList<String> convertedSet = (ArrayList<String>) Utils.StringUtils.convertFromByteString(byteString);
        VCS.getServiceManager().addConsoleLog(convertedSet.get(0));
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

public static String convertToByteString(Object object) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
            out.writeObject(object);
            final byte[] byteArray = bos.toByteArray();
            return new String(byteArray);
        }
    }

public static Object convertFromByteString(String byteString) throws IOException, ClassNotFoundException {
        final byte[] bytes = byteString.getBytes();
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
            return in.readObject();
        }
    }

最佳答案

我想通了。我不得不使用 Base64 编码。转换方法必须更改为以下内容:

public static String convertToByteString(Object object) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
            out.writeObject(object);
            final byte[] byteArray = bos.toByteArray();
            return Base64.getEncoder().encodeToString(byteArray);
        }
    }

public static Object convertFromByteString(String byteString) throws IOException, ClassNotFoundException {
        final byte[] bytes = Base64.getDecoder().decode(byteString);
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
            return in.readObject();
        }
    }

关于java - 无效的流 header : EFBFBDEF when converting object from byte string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818958/

相关文章:

php - 复选框、表单提交以及如何在循环中正确使用 array_fill?

java - 如何将 String 转换为 java.util.date 以便使其可插入 "DATE"类型的 mysql 数据库列?

javascript - 检查 Javascript 数组中是否存在标签

javascript - 多个图像阵列,单击按钮即可随机化图像

java - 通过 JNI 从 C++ 获取 java 数组

javascript - NodeJS函数被socketio事件中断

java - 将对象发送到方法

java - 在 Java 代码中使用 Eclipse 类路径变量

java - 在 CSV 文件中包含逗号

java - java中查找双引号内的子字符串