[关闭]
@xtccc 2015-10-14T08:10:34.000000Z 字数 1004 阅读 2250

Kryo Serializer

肖韬

GitHub



Kryo


在Maven中引入Kryo

  1. <dependency>
  2. <groupId>com.esotericsoftware</groupId>
  3. <artifactId>kryo</artifactId>
  4. <version>3.0.2</version>
  5. </dependency>


快速开始的简单例子

下面我们使用Kryo来将一个class(ImmutableBytesWritable)的 instance 转换成字节流写入外部文件,然后再从文件中读取里面的字节内容,并将其反序列化为该class的另一个instance。

  1. def main(args: Array[String]): Unit = {
  2. val obj = new ImmutableBytesWritable(Bytes.toBytes("Test ImmutableBytesWritable"))
  3. serialize(obj, "a.dat")
  4. deserialize("a.dat")
  5. }
  6. def serialize(obj: ImmutableBytesWritable, path:String): Unit = {
  7. val kryo = new Kryo()
  8. val output = new Output(new FileOutputStream(path))
  9. kryo.writeObject(output, obj)
  10. output.close
  11. }
  12. def deserialize(path: String): Unit = {
  13. val kryo = new Kryo()
  14. val input = new Input(new FileInputStream(path))
  15. val obj = kryo.readObject(input, classOf[ImmutableBytesWritable])
  16. .asInstanceOf[ImmutableBytesWritable]
  17. println(Bytes.toStringBinary(obj.get))
  18. input.close
  19. }



输出:

Test ImmutableBytesWritable



说明:

Output 类 : 是一个输出流,可以将数据写入到一个byte array类型的缓冲区。当 Output 将数据写到一个输出流时,它会先将数据缓存起来,当缓冲区满了才会flush。因此,当Output写完数据后,一定要调用 close 或者 'flush',这样才能保证数据真正地写入了输出流。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注