2014-04-15 9 views
6

Ho cercato 2 ore per trovare un semplice esempio su come utilizzare Kryo per serializzare un oggetto e deserializzare di nuovo. Ogni frammento di codice che ho trovato non funziona/corrisponde.si prega di fornire il codice Kryo sample

C'è qualche campione/fonte là fuori per es. Kryo 2.23.0?

risposta

6

La sintassi di Kryo è relativamente simile alla serializzazione java. Un oggetto Kryo viene creato così come uscita/ingresso e uno dei metodi kryos viene utilizzato per eseguire la serializzazione/deserialisation

  • 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

Ciascuna delle scritture è accoppiato con una lettura

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

Il seguente è un esempio utilizzando writeClassAndObject che serialises un Vector3D in un file e viceversa.

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

Tutta la documentazione fino ad oggi ha spostato a github ora; https://github.com/EsotericSoftware/kryo#quickstart

+0

Si deve notare che in questo esempio richiede Java 7. –

3

Una versione semplice:

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(); 
Problemi correlati