使用Kryo将多个对象序列化为单个文件
问题描述:
据我所知,Kryo序列化/反序列化发生在每个对象上。是否可以将多个对象序列化为单个文件?在另一个类似的SO问题中提出的另一种解决方法是使用一组对象。考虑到需要序列化的大量数据,我觉得它不会像应该那样高效。这是正确的假设吗?使用Kryo将多个对象序列化为单个文件
答
Kryo API是否需要OutputStream?如果是这样,给它提供相同的OutputStream来序列化多个文件。阅读时用InputStream做同样的事情。一个好的序列化格式将有长度编码或终止符号,并且不会依赖于EOF。
只要所有这些对象已经在内存中,数组方法也可以以最小的开销工作。你正在谈论的是为每个对象添加几个字节来创建一个数组来保存它们。如果它们不全在内存中,则必须首先将它们全部加载到内存中以在它们周围创建一个数组。鉴于足够大的数据集,这肯定会成为一个问题。
答
由于Kryo支持流式传输,所以没有什么可以阻止你在顶层写入/读取多个对象给kryo。例如,以下程序将两个不相关的对象写入文件,然后再将它们反序列化:
public class TestClass{
public static void main(String[] args) throws FileNotFoundException{
serialize();
deSerialize();
}
public static void serialize() throws FileNotFoundException{
Collection<String>collection=new ArrayList<>();
int otherData=12;
collection.add("This is a serialized collection of strings");
Kryo kryo = new Kryo();
Output output = new Output(new FileOutputStream("testfile"));
kryo.writeClassAndObject(output, collection);
kryo.writeClassAndObject(output, otherData); //we could add as many of these as we like
output.close();
}
public static void deSerialize() throws FileNotFoundException{
Collection<String>collection;
int otherData;
Kryo kryo = new Kryo();
Input input = new Input(new FileInputStream("testfile"));
collection=(Collection<String>)kryo.readClassAndObject(input);
otherData=(Integer)kryo.readClassAndObject(input);
input.close();
for(String string: collection){
System.out.println(string);
}
System.out.println("There are other things too! like; " + otherData);
}
}
序列化/反序列化期间的缓冲区/流严格映射到类。上述方法可能无法正常工作。让我尝试。 – 2011-03-09 00:34:29
对象不在内存中。所以阵列的方法将是一个问题 – 2011-03-09 00:35:20
这个答案是正确的,Kryo v2支持流式传输。将对象依次写入文件。从文件中逐一阅读。 – NateS 2012-06-15 02:47:06