Please provide sample cryo code

I searched 2 hours to find a simple example of how to use Kryo to serialize an object and deserialize it again. Each piece of code found does not work / matches.

Is there any sample / source there, for example. Kryo 2.23.0?

+6
source share
2 answers

The Kryo syntax is relatively similar to java serialization. A kryo object is created, as well as an output / input, and one of the kryos methods is used to serialize / deserialize

  • 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

Each entry is associated with reading.

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

The following is an example of using writeClassAndObject, which serializes Vector3d to and from a file.

 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()); } } 

All updated documentation has now moved to github; https://github.com/EsotericSoftware/kryo#quickstart

+6
source

Simple version:

 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(); 
+3
source

All Articles