【发布时间】:2011-03-05 04:07:36
【问题描述】:
据我所知,Kryo 序列化/反序列化发生在每个对象上。是否可以将多个对象序列化到一个文件中?在另一个类似的 SO 问题中建议的解决方法之一是使用对象数组。考虑到需要序列化的大量数据,我觉得它的效率不会达到应有的水平。这是正确的假设吗?
【问题讨论】:
标签: java serialization kryo
据我所知,Kryo 序列化/反序列化发生在每个对象上。是否可以将多个对象序列化到一个文件中?在另一个类似的 SO 问题中建议的解决方法之一是使用对象数组。考虑到需要序列化的大量数据,我觉得它的效率不会达到应有的水平。这是正确的假设吗?
【问题讨论】:
标签: java serialization 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);
}
}
【讨论】: