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

Say,

byte a[];
byte b[];

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


当前回答

最优雅的方法是使用ByteArrayOutputStream。

byte a[];
byte b[];

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

byte c[] = outputStream.toByteArray( );

其他回答

对于两个或多个数组,可以使用这个简单而干净的实用程序方法:

/**
 * 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();
}
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);

你可以使用第三方库,如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);

如果你已经在加载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;
}