在Java中,是否可以从字节数组中获取特定的字节?
我有一个字节数组:
byte[] abc = new byte[512];
我想要从这个数组中获得三个不同的字节数组:
- 字节0-127
- 字节128-255
- 字节256-511
我尝试使用abc.read(byte[], offset,length)
,但只有在offset为0时才起作用,其他任何值都会抛出IndexOutOfBoundsException
异常。
我做错了什么?
Arrays.copyOfRange()
来实现。Arrays.copyOfRange()
是Java 1.6引入的。如果您使用的是旧版本,则它在内部使用System.arraycopy(...)
。以下是其实现方式:
public static <U> U[] copyOfRange(U[] original, int from, int to) {
Class<? extends U[]> newType = (Class<? extends U[]>) original.getClass();
int newLength = to - from;
if (newLength < 0) {
throw new IllegalArgumentException(from + " > " + to);
}
U[] copy = ((Object) newType == (Object)Object[].class)
? (U[]) new Object[newLength]
: (U[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
Integer[]
传递给它并将结果分配给String[]
变量)。Arrays.copyOfRange(T[], int, int)
返回T[]
。您可能会将其与另一个带有Class
参数的版本混淆。 - finnwByteBuffer skip4Bytes = ByteBuffer.wrap(bytes, 4, bytes.length - 4);
- madx