gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:44:45 24 4
gpt4 key购买 nike

我正在尝试将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com