连接两个字节数组的简单方法是什么?

Say,

byte a[];
byte b[];

我如何连接两个字节数组,并将其存储在另一个字节数组?


当前回答

如果你喜欢像@kalefranz这样的ByteBuffer,总是可以在一行中连接两个字节[](甚至更多),就像这样:

byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();

其他回答

下面是一个很好的解决方案,使用Guava的com.google.common.primitives.Bytes:

byte[] c = Bytes.concat(a, b);

这个方法的伟大之处在于它有一个varargs签名:

public static byte[] concat(byte[]... arrays)

这意味着您可以在单个方法调用中连接任意数量的数组。

你可以使用第三方库,如Apache Commons Lang,并像这样使用它:

byte[] bytes = ArrayUtils.addAll(a, b);

最简单的:

byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);

如果你喜欢像@kalefranz这样的ByteBuffer,总是可以在一行中连接两个字节[](甚至更多),就像这样:

byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();