"java.lang.ArrayIndexOutOfBoundsException" with System.arraycopy ()

These few lines of code give me a "java.lang.ArrayIndexOutOfBoundsException", can someone please take a look and point out why (the exception was thrown in the second call to 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);

      

The problem is res size allocation, for example if I write a new byte [newContentBytes.length + headerBytes.length + 2000] instead, no exception is thrown, so what should be the exact size?

+2


a source to share


1 answer


Your index to start recording is incorrect. Try the following:



 System.arraycopy(newContentBytes, 0, res, headerBytes.length , newContentBytes.length);

      

+3


a source







All Articles