2

These few lines of code are giving me a "java.lang.ArrayIndexOutOfBoundsException" exception, could someone please take a look and point out why (the exception is caused in the second arraycopy() call):

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 in allocating res size, for example if I write new byte[newContentBytes.length + headerBytes.length+ 2000] instead the exception doesn't occur, so what should the accurate size be?

1 Answer 1

3

Your index to start writing is incorrect. Try this:

 System.arraycopy(newContentBytes, 0, res, headerBytes.length , newContentBytes.length);
Sign up to request clarification or add additional context in comments.

1 Comment

explanation please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.