我试图将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) 我有一个类Data.java
public class Data{
private String name;
private String age;
// getters and setters for the above fields
}
Run Code Online (Sandbox Code Playgroud)
在我执行的一种方法中
String newData = getData().toString();
Run Code Online (Sandbox Code Playgroud)
但现在我希望数据对象恢复其状态而不是字符串对象。那么如何在java中执行此操作。