连接两个字节数组的简单方法是什么?
Say,
byte a[];
byte b[];
我如何连接两个字节数组,并将其存储在另一个字节数组?
连接两个字节数组的简单方法是什么?
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();
}
其他回答
最简单的:
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[] 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);
下面是一个很好的解决方案,使用Guava的com.google.common.primitives.Bytes:
byte[] c = Bytes.concat(a, b);
这个方法的伟大之处在于它有一个varargs签名:
public static byte[] concat(byte[]... arrays)
这意味着您可以在单个方法调用中连接任意数量的数组。
另一种可能是使用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()只是返回支持数组,而不考虑偏移量、位置或限制)。
合并两个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();