6

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

4

2 回答 2

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

于 2014-05-09T13:12:53.110 回答
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();
于 2016-02-22T14:14:46.663 回答