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

Say,

byte a[];
byte b[];

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


当前回答

最优雅的方法是使用ByteArrayOutputStream。

byte a[];
byte b[];

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

byte c[] = outputStream.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 byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, 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代码的优势,而且非常易于阅读和维护。

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

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

合并两个PDF字节数组

如果合并两个包含PDF的字节数组,则此逻辑将不起作用。我们需要使用第三方工具,如Apache中的PDFbox:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
mergePdf.addSource(new ByteArrayInputStream(a));
mergePdf.addSource(new ByteArrayInputStream(b));
mergePdf.setDestinationStream(byteArrayOutputStream);
mergePdf.mergeDocuments();
c = byteArrayOutputStream.toByteArray();