[英]How to (de)serialize correctly to a byte-array using a ObjectOutputStream & ObjectInputStream?
I am aware that an ObjectOutputStream/ObjectInputStream uses headers and this is not really a proper use-case. 我知道ObjectOutputStream / ObjectInputStream使用标头,这实际上不是一个合适的用例。 But anyway I need to wrap some data into it using the interfaces DataInput and DataOutput.
但是无论如何,我需要使用DataInput和DataOutput接口将一些数据包装到其中。
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
byte[] array = serialize("test");
String deserialized = deserialize(array);
System.out.println(deserialized);
}
private static byte[] serialize(String test) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeUTF(test);
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toByteArray();
}
private static String deserialize(byte[] array) {
String temp = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(array));
temp = objectInputStream.readUTF();
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
}
I don't really get how to get that working. 我真的不知道如何使它工作。 Am I right, that the problem are those headers currently?
我是对的,现在的问题是这些标题吗?
You should call objectOutputStream.flush();
您应该调用
objectOutputStream.flush();
before closing byteArrayOutputStream
. 在关闭
byteArrayOutputStream
之前。
ObjectOutputStream
have its internal buffer so you got only beginning of string in your byte array. ObjectOutputStream
有其内部缓冲区,因此您只能在字节数组中获得字符串的开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.