是否可以从java中的字节数组中获取特定字节?
我有一个字节数组:
byte[] abc = new byte[512];
我想从这个数组中获得3个不同的字节数组。
我尝试了abc.read(byte[], offset,length)
,但只有当我将偏移量设为0时才有效,对于任何其他值,它会抛出IndexOutOfbounds
异常。
我做错了什么?
答案 0 :(得分:63)
您可以使用Arrays.copyOfRange()
。
答案 1 :(得分:14)
Arrays.copyOfRange()
。如果您使用的是旧版本,则会在内部使用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;
}
答案 2 :(得分:1)
您也可以在原始数组的顶部使用字节缓冲区作为视图。