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

Say,

byte a[];
byte b[];

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


当前回答

如果你不想打乱数组的大小,只需使用字符串连接的魔法:

byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");

或者在代码的某个地方定义

// concatenation charset
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;

和使用

byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);

当然,这也适用于使用+加法运算符的两个以上的字符串连接。


“l1”和ISO_8859_1都表示将每个字符编码为单个字节的西方拉丁1字符集。由于没有执行多字节转换,字符串中的字符将具有与字节相同的值(除了它们总是被解释为正值,因为char是无符号的)。至少对于Oracle提供的运行时,任何字节都将因此被正确地“解码”,然后再次“编码”。

注意,字符串确实会适当地扩展字节数组,需要额外的内存。字符串也可能被扣押,因此不容易被删除。字符串也是不可变的,所以其中的值不能被销毁。因此,不应以这种方式连接敏感数组,也不应将此方法用于较大的字节数组。还需要清楚地表明您正在做什么,因为这种数组连接方法不是常见的解决方案。

其他回答

最简单的:

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);

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

byte[] bytes = ArrayUtils.addAll(a, b);
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);

另一种方法是使用一个实用函数(如果你喜欢,你可以让它成为一个通用实用类的静态方法):

byte[] concat(byte[]...arrays)
{
    // Determine the length of the result array
    int totalLength = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        totalLength += arrays[i].length;
    }

    // create the result array
    byte[] result = new byte[totalLength];

    // copy the source arrays into the result array
    int currentIndex = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
        currentIndex += arrays[i].length;
    }

    return result;
}

像这样调用:

byte[] a;
byte[] b;
byte[] result = concat(a, b);

它也可以用于连接3,4,5个数组等。

这样做可以获得快速arraycopy代码的优势,而且非常易于阅读和维护。

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

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