使用kryo序列化

2017-03-20  本文已影响686人  pyboy

pom.xml 配置

<dependency>
    <groupId>com.esotericsoftware</groupId>
    <artifactId>kryo</artifactId>
    <version>3.0.3</version>
</dependency>

android配置
build.gradle

dependencies {
    compile 'com.esotericsoftware:kryo:3.0.3'
}

github地址

快速入手

Kryo kryo = new Kryo();
// 写
Output output = new Output(new FileOutputStream("file.data"));
SomeClass someObject = ...
kryo.writeObject(output, someObject);
output.close();
// 读
Input input = new Input(new FileInputStream("file.data"));
SomeClass someObject = kryo.readObject(input, SomeClass.class);
input.close();

序列化

 /**
     * 对象序列化
     * 
     * @param value
     * @return
     */
    protected byte[] value(Object value) {
        try {
            Kryo kryo = new Kryo();
            byte[] buffer = new byte[2048];
            Output output = new Output(buffer);
            kryo.writeClassAndObject(output, value);
            return output.toBytes();
        } catch (Exception e) {
            return null;
        }
    }
/**
 * 对象反序列化
 * 
 * @param value
 * @return
 */
protected Object object(byte[] value) {
    try {
        Kryo kryo = new Kryo();
        Input input = new Input(value);
        return kryo.readClassAndObject(input);
    } catch (Exception e) {
        return null;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读