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

Say,

byte a[];
byte b[];

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


当前回答

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

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

其他回答

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

最优雅的方法是使用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);

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

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提供的运行时,任何字节都将因此被正确地“解码”,然后再次“编码”。

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