查了Arrays.copyOfRange(byte[] original, int from, int to)的出处
public static byte[] copyOfRange(byte[] original, int from, int to) {
1 int newLength = to - from;
2 if (newLength < 0)
3 throw new IllegalArgumentException(from + " > " + to);
4 byte[] copy = new byte[newLength];
5 System.arraycopy(original, from, copy, 0,
6 Math.min(original.length - from, newLength));
7 return copy;
}
如果您的from 是bytes.length + 1,则length 为负数(bytes.length - from)。
一个小代码来演示
public class ArrayCopy {
public static void main(String[] args) {
byte[] bytes = new byte[]{11, 12, 13};
int from = 3;
int to = 4;
copyOfRange(bytes, from, to);
from = 2;
to = 3;
copyOfRange(bytes, from, to);
from = 4;
to = 5;
copyOfRange(bytes, from, to);
}
static void copyOfRange(byte[] bytes, int from, int to) {
System.out.printf("%ncopyOfRange(bytes: %s from: %d to: %d)%n",
Arrays.toString(bytes),
from,
to
);
// line 1
int newLength = to - from;
System.out.println("int newLength = " + newLength);
// line 2
if (newLength < 0) {
throw new IllegalArgumentException(from + " > " + to);
}
// line 4
byte[] copy = new byte[newLength];
// to show that in the suspicious case System.arrayCopy does nothing
copy[0] = 42;
System.out.println("byte[] copy = " + Arrays.toString(copy));
int length = bytes.length - from;
System.out.println("int length = " + length);
int minLenght = Math.min(length, newLength);
System.out.println("int minLenght = " + minLenght);
// line 5
System.arraycopy(bytes, from, copy, 0, minLenght);
System.out.println("byte[] copy = " + Arrays.toString(copy));
}
}
输出
copyOfRange(bytes: [11, 12, 13] from: 3 to: 4)
int newLength = 1
byte[] copy = [42]
int length = 0
int minLenght = 0
byte[] copy = [42]
copyOfRange(bytes: [11, 12, 13] from: 2 to: 3)
int newLength = 1
byte[] copy = [42]
int length = 1
int minLenght = 1
byte[] copy = [13]
copyOfRange(bytes: [11, 12, 13] from: 4 to: 5)
int newLength = 1
byte[] copy = [42]
int length = -1
int minLenght = -1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException