我发现了两种通用的使用Kryo读写的方法,我在想它们中的一种是好的还是坏的,或者它们是一样的。
选项1-使用kryo函数writeClassAndObject (readClassAndObject)
public <T> void writeK(T obj, String fileName) {
checkDir(path);
Kryo kryo = new Kryo();
Output output = null;
try {
output = new Output(new FileOutputStream(homePath + path + "/" + "kryo_" + fileName + ".bin"));
kryo.writeClassAndObject(output, obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
output.close();
}}
选项2-使用writeObject (readObject)和类信息
public <T> void writeKryo(Class<T> cl, T obj, String fileName) {
checkDir(path);
Kryo kryo = new Kryo();
kryo.register(cl);
Output output = null;
try {
output = new Output(new FileOutputStream(homePath + path + "/" + "kryo_" + fileName + ".bin"));
kryo.writeObject(output, obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
output.close();
}
}第二个选项似乎更好,因为在调用函数时,我指定了那个类是什么类,这样Java就不需要弄清楚自己了。但不确定这是不是真的。从速度上看,它们似乎是相当的。谢谢
发布于 2015-05-12 08:08:46
这取决于您是否能够从上下文中了解序列化数据在反序列化数据时表示的类的实例。使用writeClassAndObject时,在读取对象时不需要指定类。您可以反序列化数据,然后在此实例上调用getClass。
相反,在使用writeObject时,在读取存储对象时确实需要知道它的类。否则,无法反序列化数据,因为信息未存储在序列化数据中。
当(反序列化一个对象)时,选择哪种方法并不重要,因为您可以同时选择这两种方法。但是,设想一次又一次序列化同一个类的实例的场景。当不使用每个实例存储类时,序列化数据的大小可以大大减小。相反,您可以在文件开始时序列化类名,甚至可以将其硬编码到反序列化器中。
https://stackoverflow.com/questions/30184019
复制相似问题