Java 序列化--- Kryo使用简单例子

Java 序列化--- Kryo使用简单例子

简单示例

       Kryo kryo = new Kryo();

       Input input = null;

       input = new Input(new FileInputStream(fileName));

       BackupQueueData queueData = kryo.readObject(input, BackupQueueData.class);

        Kryo kryo = new Kryo();

        Output output = null;

output = new Output(new FileOutputStream(fileName));

        kryo.writeObject(output, queueData);                

 

Kryo.Pool

KryoFactory factory = new KryoFactory() {

           public Kryo create() {

              Kryo kryo = new Kryo();

              returnkryo;

           }

       };

       // Simple pool, you might also activate SoftReferences to fight OOMEs.

       KryoPool pool = new KryoPool.Builder(factory).build();

       Kryo kryo = pool.borrow();

       Output output = new Output(new FileOutputStream("Test.file"));

       TestBean tb = new TestBean();

       tb.setId(1L);

       tb.setAge(20);

       kryo.writeObject(output, tb);

       output.close();

       pool.release(kryo);

 

       // or use a callback to work with kryo (pool.run borrows+releases for

       // you)

      

       TestBean value = pool.run(new KryoCallback() {

           public TestBean execute(Kryo kryo) {

              Input input;

              try {

                  input = new Input(new FileInputStream("Test.file"));

                  returnkryo.readObject(input, TestBean.class);

              } catch (FileNotFoundException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

              returnnull;

           }

       });

        System.out.println(value.getId());

                System.out.println(value.getAge());

Kryo池并不复杂,提供了除了直接构建Kryo实例之外的另一种是用方式。


你可能感兴趣的:(java)