我正在尝试使用kryo对Java集合进行序列化和反序列化。
序列化方法如下所示:
public <T> byte[] serialize(List<T> objectsToSerialize) {
CollectionSerializer cs = new CollectionSerializer();
Output output = new Output();
cs.write(kryo, output, objectsToSerialize);
return output.toBytes();
}
现在,我想编写反序列化方法,但是这样做很麻烦。基本上,CollectionSerializer具有读取方法,但我不明白如何使用它(据我所知,文档非常差)。
有任何想法吗?
如果您只想将a序列化Collection
到文件,则标准Kryo命令(例如kryo.writeClassAndObject
)可以很好地处理该问题。例如,以下程序将字符串的集合传递到文件“ testfile”,然后再次返回
public class TestClass{
public static void main(String[] args) throws FileNotFoundException{
serialize();
deSerialize();
}
public static void serialize() throws FileNotFoundException{
Collection<String>collection=new ArrayList<>();
collection.add("This is a serialized collection of strings");
Kryo kryo = new Kryo();
Output output = new Output(new FileOutputStream("testfile"));
kryo.writeClassAndObject(output, collection);
output.close();
}
public static void deSerialize() throws FileNotFoundException{
Collection<String>collection;
Kryo kryo = new Kryo();
Input input = new Input(new FileInputStream("testfile"));
collection=(Collection<String>)kryo.readClassAndObject(input);
input.close();
for(String string: collection){
System.out.println(string);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句