如何使用Kryo序列化对象并再次反序列化?

时间:2014-04-15 11:16:18

标签: java serialization kryo

如何使用Kryo序列化对象并再次反序列化?我在Kryo 2.23.0

工作

2 个答案:

答案 0 :(得分:7)

Kryo的语法与java序列化相似。创建kryo对象以及输出/输入,并使用kryos方法之一来执行序列化/反序列化

  • kryo.writeClassAndObject(output, object); //for if the concrete class isn't known (can be null)
  • kryo.writeObjectOrNull(output, someObject); //if the object could be null
  • kryo.writeObject(output, someObject); //can't be null and concrete class is known

每次写入都与读取

配对
  • SomeClass object = (SomeClass)kryo.readClassAndObject(input);
  • SomeClass someObject = kryo.readObjectOrNull(input, SomeClass.class);
  • SomeClass someObject = kryo.readObject(input, SomeClass.class);

以下是使用writeClassAndObject的示例,该函数将Vector3d序列化为文件并再次返回。

public class KryoTest {
    public static void main(String[] args){

        Vector3d someObject=new Vector3d(1,2,3);

        //serialise object

        //try-with-resources used to autoclose resources
        try (Output output = new Output(new FileOutputStream("KryoTest.ser"))) {
            Kryo kryo=new Kryo();
            kryo.writeClassAndObject(output, someObject);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(KryTest.class.getName()).log(Level.SEVERE, null, ex);
        }

        //deserialise object

        Vector3d retrievedObject=null;

        try (Input input = new Input( new FileInputStream("KryoTest.ser"))){
            Kryo kryo=new Kryo();
            retrievedObject=(Vector3d)kryo.readClassAndObject(input);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(KryTest.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Retrieved from file: " + retrievedObject.toString());
    }
}

所有最新文档现已转移到github; https://github.com/EsotericSoftware/kryo#quickstart

答案 1 :(得分:3)

简单版本:

Kryo kryo = new Kryo();
// #### Store to disk...
Output output = new Output(new FileOutputStream("file.bin"));
SomeClass someObject = ...
kryo.writeObject(output, someObject);
output.close();
// ### Restore from disk...
Input input = new Input(new FileInputStream("file.bin"));
SomeClass someObject = kryo.readObject(input, SomeClass.class);
input.close();