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

Say,

byte a[];
byte b[];

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


当前回答

如果你已经在加载Guava库,你可以使用静态方法concat(byte[]…从com.google.common.primitives.Bytes:

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

下面是concat(byte[]…数组)方法由“Kevin Bourrillion”:

public static byte[] concat(byte[]... arrays) {
    int length = 0;
    for (byte[] array : arrays) {
        length += array.length;
    }
    byte[] result = new byte[length];
    int pos = 0;
    for (byte[] array : arrays) {
        System.arraycopy(array, 0, result, pos, array.length);
        pos += array.length;
    }
    return result;
}

其他回答

另一种可能是使用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()只是返回支持数组,而不考虑偏移量、位置或限制)。

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

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

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

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

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

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

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

最优雅的方法是使用ByteArrayOutputStream。

byte a[];
byte b[];

ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );

byte c[] = outputStream.toByteArray( );