我在下面的代码中得到了ArrayIndexOutOfBoundsException:
String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
String endBoundary = "rn--" + boundary + "--rn";
byte[] temp = new byte[boundaryMessage.getBytes().length+fileBytes.length+endBoundary.getBytes().length];
temp = boundaryMessage.getBytes();
try {
System.arraycopy(fileBytes, 0, temp, temp.length, fileBytes.length); //exception thrown here
System.arraycopy(endBoundary.getBytes(), 0, temp, temp.length, endBoundary.getBytes().length);
}
catch(Exception e){
System.out.println("====Exception: "+e.getMessage()+" Class: "+e.getClass());
}
有人可以指出我错在哪里吗?谢谢。
当您选择 temp.length
作为dst_position参数时,您错误地使用第四个参数来数组复制。这意味着您希望在temp
数组末尾之后启动目标。第一次尝试写入数组末尾会导致ArrayIndexOutOfBoundsException
,就像您所看到的一样。 检查文档:
公共静态空数组复制(Object src, 国际src_position, 对象 dst, int dst_position, 整数长度)
将数组从指定的源阵列(从指定位置开始)复制到目标阵列的指定位置。数组组件的子序列从 src 引用的源数组复制到 dst 引用的目标数组。复制的组件数等于长度参数。源数组中 srcOffset 到 srcOffset+length-1 位置的分量分别通过 dstOffset+length-1 复制到目标数组的 dstOffset 位置。
编辑 22 1月
您的问题行如下所示:
System.arraycopy(fileBytes, 0, temp, temp.length, fileBytes.length);
如果我理解你想正确做什么,你应该能够通过将 temp.length 更改为 0 来修复它,这意味着你想将 fileBytes 复制到 temp 的开头:
System.arraycopy(fileBytes, 0, temp, 0, fileBytes.length);