kryo实现序列化至硬盘与从硬盘反序列

1.依赖


    
      com.esotericsoftware
      kryo
      4.0.2
    

2.工具类

/**
     * 序列化至硬盘
     * @param filePath  序列化路径
     * @param list      带序列号列表
     * @param        泛型
     */
    public static  void serializeObject(String filePath, List list) {

        if (CollectionUtils.isEmpty(list)) {
            LOGGER.warn("没有要待序列化的东西");
        }

        Kryo kryo = new Kryo();
        kryo.setReferences(false);
        kryo.setRegistrationRequired(false);
        kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());

        Output output = null;
        try {
            Path path = Paths.get(filePath);
            if (Files.notExists(path)) {
                Files.createFile(path);
            }
            output = new Output(new FileOutputStream(filePath));
            T t = list.get(0);
            kryo.register(t.getClass());
            kryo.writeObject(output, t);

            for (int i = 1; i < list.size(); i++) {
                T instance = list.get(i);
                kryo.writeObject(output, instance);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.warn(e.getMessage(), e.fillInStackTrace());
        } finally {
            if (output != null) {
                output.close();
            }
        }
    }

    /**
     * 反序列化至类
     * @param filePath  序列化文件路径
     * @param clazz     反序列化class类名
     * @param        泛型
     * @return          反序列化后的类
     */
    public static List deserializeObject(String filePath,Class clazz) {
        Path path = Paths.get(filePath);
        if (Files.notExists(path) || Files.isDirectory(path)) {
            LOGGER.warn("反序列化文件不存在,或不是文件");
            return null;
        }
        if(clazz == null){
            LOGGER.warn("反序列化的类为null");
            return null;
        }

        List list = Lists.newArrayList();
        Kryo kryo = new Kryo();
        kryo.setReferences(false);
        kryo.setRegistrationRequired(false);
        kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
        Input input = null;
        try {
            T t;
            input = new Input(new FileInputStream(filePath),10240);
            while (input.canReadInt()){
                t = kryo.readObject(input,clazz);
                list.add(t);
            }
        }catch (IOException e){
            e.printStackTrace();
            LOGGER.error(e.getMessage(),e.fillInStackTrace());
        }finally {
            if(input != null){
                input.close();
            }
        }

        return list;
    }

3.测试:

class Demo{
    private String name;
    private int age;

    public Demo(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Demo{name='" + name + '\'' +", age=" + age +'}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
public static void main(String[] args) {
        List demoList = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
            Demo demo = new Demo("name"+i,i);
            demoList.add(demo);
        }
        serializeObject("d:\\test.bin",demoList);

        List deserialize = deserializeObject("d:\\test.bin", Demo.class);
        if(CollectionUtils.isNotEmpty(deserialize)){
            for (Demo demo :deserialize) {
                System.out.println(demo);
            }
        }
    }

4.结果展示:

Demo{name='name0', age=0}
Demo{name='name1', age=1}
Demo{name='name2', age=2}
Demo{name='name3', age=3}
Demo{name='name4', age=4}
Demo{name='name5', age=5}
Demo{name='name6', age=6}
Demo{name='name7', age=7}
Demo{name='name8', age=8}
Demo{name='name9', age=9}

 

你可能感兴趣的:(其它)