我试图将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 = …Run Code Online (Sandbox Code Playgroud)