Gzip元组序列然后再次解压缩为元组序列 - 解压缩序列时出现问题

时间:2017-08-12 23:30:06

标签: arrays scala apache-spark gzip

我有一系列元组,我需要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现在是一个具有上面格式的String(包含单词List)。

例如:

x.toList
res174: List[Char] = List(L, i, s, t, (, (, a, ,, 1, ), ,,  , (, b, ,, 2, ), ))

我的问题是,如何将我的确切序列解压缩,或者如何将x再次转换为我之前的序列?

1 个答案:

答案 0 :(得分:0)

使用play api json库解决它,以便在json对象中存储内容:

val arr = Json.toJson(Array(Json.obj("name"-> "Bran", "age" -> 13),Json.obj("name"-> "Jon", "age" -> 18)))

val arr_bytes = arr.toString().getBytes

val comp = compress(arr_bytes)

val x= unzip(comp)

val json = Json.parse(x)