Kryo Serializer
标签: Kryo Serialization
使用Kryo简单例子
下面我们使用Kryo来将一个class(ImmutableBytesWritable
)的 instance 转换成字节流写入外部文件,然后再从文件中读取里面的字节内容,并将其反序列化为该class的另一个instance。
def main(args: Array[String]): Unit = {
val obj = new ImmutableBytesWritable(Bytes.toBytes("Test ImmutableBytesWritable"))
serialize(obj, "a.dat")
deserialize("a.dat")
}
def serialize(obj: ImmutableBytesWritable, path:String): Unit = {
val kryo = new Kryo()
val output = new Output(new FileOutputStream(path))
kryo.writeObject(output, obj)
output.close
}
def deserialize(path: String): Unit = {
val kryo = new Kryo()
val input = new Input(new FileInputStream(path))
val obj = kryo.readObject(input, classOf[ImmutableBytesWritable])
.asInstanceOf[ImmutableBytesWritable]
println(Bytes.toStringBinary(obj.get))
input.close
}
输出:
Test ImmutableBytesWritable