gpt4 book ai didi

java - "java.lang.ArrayIndexOutOfBoundsException"与 System.arraycopy()

转载 作者:行者123 更新时间:2023-12-04 06:54:30 25 4
gpt4 key购买 nike

这几行代码给了我一个“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 大小,例如,如果我写
new byte[newContentBytes.length + headerBytes.length+ 2000] 而不会发生异常,那么准确的大小应该是多少?

最佳答案

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

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

关于java - "java.lang.ArrayIndexOutOfBoundsException"与 System.arraycopy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2697776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com