質問

I'm trying a small program that would read a file, convert that to a array of bytes and zip the bytes and return the zipped bytes back as an array. However, I'm getting IndexOutOfBounds thrown. Here is what I have so far tried!

private def getBytePayload(): Array[Byte] = {
  val inputJson: String = Source.fromURL(getClass.getResource("/small_json.txt")).mkString

  val bin: ByteArrayInputStream = new ByteArrayInputStream(inputJson.getBytes())
  val bos: ByteArrayOutputStream = new ByteArrayOutputStream()

  println("The unCompressed stream size is = " + inputJson.size) // Prints 5330

  val gzip: GZIPOutputStream = new GZIPOutputStream(bos)

  val buff = new Array[Byte](1024)

  var len = 0
  while((len = bin.read(buff)) != -1) {
    gzip.write(buff, 0, len) // java.lang.IndexOutOfBoundsException is thrown!
  }

  println("The compressed stream size is = " + bos.toByteArray.size)

  bos.toByteArray
}

Any pointers as to what has gone wrong?

役に立ちましたか?

解決

As far as what the problem is, I'm not exactly sure. However, the following code should be revealing. See what it it tells you:

val buff = new Array[Byte](1024)

var len = 0
while((len = bin.read(buff)) != -1) {

   //Print out actual contents of buff:

   for(int i = 0; i < buff.length; i++)  {
      System.out.print(i + "=" + buff[i] + ", ");
   }
   System.out.println();

   gzip.write(buff, 0, len) // java.lang.IndexOutOfBoundsException is thrown!
}

This is just my style-opinion, but I personally find this confusing

while((len = bin.read(buff)) != -1) {

and would change it to

len = bin.read(buff);
while(len != -1)  {

   //do stuff

   len = bin.read(buff);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top