连接两个字节数组的简单方法是什么?
Say,
byte a[];
byte b[];
我如何连接两个字节数组,并将其存储在另一个字节数组?
连接两个字节数组的简单方法是什么?
Say,
byte a[];
byte b[];
我如何连接两个字节数组,并将其存储在另一个字节数组?
当前回答
你可以使用第三方库,如Apache Commons Lang,并像这样使用它:
byte[] bytes = ArrayUtils.addAll(a, b);
其他回答
另一种可能是使用java.nio.ByteBuffer。
类似的
ByteBuffer bb = ByteBuffer.allocate(a.length + b.length + c.length);
bb.put(a);
bb.put(b);
bb.put(c);
byte[] result = bb.array();
// or using method chaining:
byte[] result = ByteBuffer
.allocate(a.length + b.length + c.length)
.put(a).put(b).put(c)
.array();
请注意,数组必须在开始时具有适当的大小,因此需要分配行(因为array()只是返回支持数组,而不考虑偏移量、位置或限制)。
如果你喜欢像@kalefranz这样的ByteBuffer,总是可以在一行中连接两个字节[](甚至更多),就像这样:
byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();
这就是我的方法!
public static byte[] concatByteArrays(byte[]... inputs) {
int i = inputs.length - 1, len = 0;
for (; i >= 0; i--) {
len += inputs[i].length;
}
byte[] r = new byte[len];
for (i = inputs.length - 1; i >= 0; i--) {
System.arraycopy(inputs[i], 0, r, len -= inputs[i].length, inputs[i].length);
}
return r;
}
特点:
使用varargs(…)来调用任意数量的字节[]。 使用System.arraycopy(),它是由机器特定的本机代码实现的,以确保高速运行。 创建一个新字节[],其大小与所需要的大小一致。 通过重用i和len变量来分配更少的int变量。 与常数比较更快。
请记住:
更好的方法是复制@Jonathan代码。问题来自本地变量数组,因为当此数据类型传递给另一个函数时,Java会创建新的变量。
下面是一个很好的解决方案,使用Guava的com.google.common.primitives.Bytes:
byte[] c = Bytes.concat(a, b);
这个方法的伟大之处在于它有一个varargs签名:
public static byte[] concat(byte[]... arrays)
这意味着您可以在单个方法调用中连接任意数量的数组。
对于两个或多个数组,可以使用这个简单而干净的实用程序方法:
/**
* Append the given byte arrays to one big array
*
* @param arrays The arrays to append
* @return The complete array containing the appended data
*/
public static final byte[] append(final byte[]... arrays) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (arrays != null) {
for (final byte[] array : arrays) {
if (array != null) {
out.write(array, 0, array.length);
}
}
}
return out.toByteArray();
}