2010-04-23 79 views
2

這幾行代碼給了我一個「java.lang.ArrayIndexOutOfBoundsException」異常,有人可以請看看並指出原因(異常是由於第二arraycopy()調用):「java.lang.ArrayIndexOutOfBoundsException」with System.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); 

的問題是在分配資源的大小,例如,如果我寫 新的字節[newContentBytes.length + headerBytes.length + 2000]代替異常不發生,所以準確的大小應該是什麼?

回答

3

您的索引開始寫入不正確。試試這個:

System.arraycopy(newContentBytes, 0, res, headerBytes.length , newContentBytes.length); 
相關問題