質問

I'm looking to roundtrip bytes through java's Deflater and running into issues. First the output, then the code. What am I doing wrong here, and how can I properly round trip through these streams?

Output:

scala> new String(decompress(compress("face".getBytes)))
(crazy output string of length 20)

Code:

  def compress(bytes: Array[Byte]): Array[Byte] = {
    val deflater = new java.util.zip.Deflater
    val baos = new ByteArrayOutputStream
    val dos = new DeflaterOutputStream(baos, deflater)
    dos.write(bytes)
    baos.close
    dos.finish
    dos.close
    baos.toByteArray
  }

  def decompress(bytes: Array[Byte]): Array[Byte] = {
    val deflater = new java.util.zip.Deflater
    val baos = new ByteArrayOutputStream(512)
    val bytesIn = new ByteArrayInputStream(bytes)
    val in = new DeflaterInputStream(bytesIn, deflater)
    var go = true
    while (go) {
      val b = in.read
      if (b == -1)
        go = false
      else
        baos.write(b)
    }
    baos.close
    in.close
    baos.toByteArray
  }
役に立ちましたか?

解決

You're (re-)Deflater-ing the result of the original deflation when you should be Inflater-ing it...

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top