![](/img/trans.png)
[英]java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
[英]invalid stream header: EFBFBDEF when converting object from byte string
我试图将ArrayList对象转换为字节字符串,以便它可以通过套接字发送。 当我运行此代码时,它会正确转换为字符串,但是当我尝试将其转换回来时,我得到异常“java.io.StreamCorruptedException:invalid stream 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();
}
}
String不是二进制数据的容器。 您需要传递原始字节数组,或对其进行hex或base64编码。
更好的是,直接序列化到套接字并完全摆脱它。
我想到了。 我不得不使用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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.