System.arraycopy()的“java.lang.ArrayIndexOutOfBoundsException”

时间:2010-04-23 10:25:29

标签: java exception

这几行代码给我一个“java.lang.ArrayIndexOutOfBoundsException”异常,有人可以看看并指出原因(异常是在第二次arraycopy()调用中引起的):

byte [] newContentBytes = EntityUtils.toByteArray((serverResponse.getEntity()));
  newContent = new String(newContentBytes);
  System.out.println( newContent);
  byte [] headerBytes = headers.getBytes();
  byte[] res = new byte[newContentBytes.length + headerBytes.length];
  //headerBytes.
  System.arraycopy(headerBytes, 0, res, 0, headerBytes.length);
  System.out.println( "length: " + newContentBytes.length);
  System.arraycopy(newContentBytes, 0, res, newContentBytes.length , newContentBytes.length);

问题在于分配res大小,例如,如果我写 新字节[newContentBytes.length + headerBytes.length + 2000]而不会发生异常,那么准确的大小应该是什么?

1 个答案:

答案 0 :(得分:3)

您开始撰写的索引不正确。试试这个:

 System.arraycopy(newContentBytes, 0, res, headerBytes.length , newContentBytes.length);
相关问题