kryo 序列化

package com.#.vde.compiler.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.telenav.vde.compiler.feature.CityFeature;

public class KryoHelper {

    public static <T> Kryo getKryo(Class<T> clazz) {
        Kryo kryo = new Kryo();
        kryo.setReferences(false);
        kryo.setRegistrationRequired(true);

        CollectionSerializer serializer = new CollectionSerializer();
        serializer.setElementClass(clazz, new JavaSerializer());
        serializer.setElementsCanBeNull(false);

        kryo.register(clazz, new JavaSerializer());
        kryo.register(ArrayList.class, serializer);

        return kryo;
    }

    /**
     * Serialization object to file through kryo
     * 
     * @param <T>
     * 
     * @param <T>
     * 
     * @param citylist
     * @param filename
     */
    public static <T extends Serializable> void setSerializationObjectByKryo(List<T> citylist, Class<T> clazz,
            String filename) {
        Date time0 = new Date();

        try {
            Kryo kryo = getKryo(clazz);

            Output output = new Output(new FileOutputStream(filename));
            kryo.writeObject(output, citylist);

            System.out.println("write done " + filename);
            System.out.println("time cost/ms : " + ((new Date()).getTime() - time0.getTime()));

            output.flush();
            output.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(-1);
        }
    }

    /**
     * get the serialization object
     * 
     * @param <T>
     * 
     * @param cla
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> List<T> getSerializationObjectByKryo(String filename, Class<T> clazz) {
        Date time0 = new Date();

        Kryo kryo = getKryo(clazz);

        Input input;
        try {
            input = new Input(new FileInputStream(filename));

            List<T> citylist = kryo.readObject(input, ArrayList.class);

            input.close();

            System.out.println("read done");
            System.out.println("time cost " + ((new Date()).getTime() - time0.getTime()));
            return citylist;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

posted @ 2017-09-19 18:09  百变小超  阅读(1538)  评论(0编辑  收藏  举报