@xtccc
2015-10-14T08:10:34.000000Z
字数 1004
阅读 2606
肖韬
GitHub
Kryo
<dependency><groupId>com.esotericsoftware</groupId><artifactId>kryo</artifactId><version>3.0.2</version></dependency>
下面我们使用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
说明:
Output类 : 是一个输出流,可以将数据写入到一个byte array类型的缓冲区。当Output将数据写到一个输出流时,它会先将数据缓存起来,当缓冲区满了才会flush。因此,当Output写完数据后,一定要调用close或者 'flush',这样才能保证数据真正地写入了输出流。
