IndexOutOfBounds异常

时间:2014-02-20 14:50:39

标签: scala gzip

我正在尝试一个能够读取文件的小程序,将其转换为字节数组并压缩字节并将压缩后的字节作为数组返回。但是,我正在抛出IndexOutOfBounds。这是我到目前为止所尝试的内容!

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
}

关于出了什么问题的任何指示?

1 个答案:

答案 0 :(得分:1)

就问题而言,我并不完全确定。但是,以下代码应该是透露的。看看它告诉你的是什么:

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!
}

这只是我的风格意见,但我个人认为这令人困惑

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

并将其更改为

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

   //do stuff

   len = bin.read(buff);
}