【发布时间】:2017-08-12 23:30:05
【问题描述】:
我有一个元组序列,我需要对其进行 gzip 压缩以进行存储。之后我希望能够提取压缩内容,解压缩,然后返回元组序列。
我使用以下代码进行解压缩:
def unzip(x: Array[Byte]) : String = {
val inputStream = new GZIPInputStream(new ByteArrayInputStream(x))
val output = scala.io.Source.fromInputStream(inputStream).mkString
return output
}
def gzip(input: Array[Byte]): Array[Byte] = {
val bos = new ByteArrayOutputStream(input.length)
val gzip = new GZIPOutputStream(bos)
gzip.write(input)
gzip.close()
val compressed = bos.toByteArray
bos.close()
compressed
}
取自此来源https://gist.github.com/owainlewis/1e7d1e68a6818ee4d50e。
那我的套路或多或少是这样的:
val arr = Seq(("a",1),("b",2))
val arr_bytes = arr.toString.getBytes
val comp = compress(arr_bytes)
val x = unzip(comp)
输出如下:
arr: Seq[(String, Int)] = List((a,1), (b,2))
arr_bytes: Array[Byte] = Array(76, 105, 115, 116, 40, 40, 97, 44, 49, 41, 44, 32, 40, 98, 44, 50, 41, 41)
comp: Array[Byte] = Array(31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, -55, 44, 46, -47, -48, 72, -44, 49, -44, -44, 81, -48, 72, -46, 49, -46, -44, 4, 0, 35, 120, 118, -118, 18, 0, 0, 0)
x: String = List((a,1), (b,2))
问题是 x 现在是一个具有上述格式的字符串(也包含单词 List)。
例如:
x.toList
res174: List[Char] = List(L, i, s, t, (, (, a, ,, 1, ), ,, , (, b, ,, 2, ), ))
我的问题是,我如何将我的确切序列解压缩回来,或者如何将 x 再次变成我之前的序列?
【问题讨论】:
-
您正在向流中写入一个字符串,然后从流中读取一个字符串......然后很惊讶,您得到了字符串?
-
您是否测试过使用任何已知的可用序列化库来序列化您的数据?例如,您可以使用 Jackson Scala 模块 (github.com/FasterXML/jackson-module-scala) 将序列化对象映射回 scala 类。
-
嘿 Miguel,是的,这就是我最终做的事情,并且成功了 :)
标签: arrays scala apache-spark gzip