To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.
You can only concatenate a sequence with another sequence. bytes(a[0]) gives you that because a[0] is an integer, and as documented doing bytes(someInteger) gives you a sequence of that many zero bytes (e.g,, bytes(3) gives you 3 zero bytes). {a[0]} is a set.
The most elegant way to do this is with a ByteArrayOutputStream
.
byte a[];
byte b[];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );
byte c[] = outputStream.toByteArray( );
Most straightforward:
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);
Here's a nice solution using Guava's com.google.common.primitives.Bytes
:
byte[] c = Bytes.concat(a, b);
The great thing about this method is that it has a varargs signature:
public static byte[] concat(byte[]... arrays)
which means that you can concatenate an arbitrary number of arrays in a single method call.
Another possibility is using java.nio.ByteBuffer
.
Something like
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();
Note that the array must be appropriately sized to start with, so the allocation line is required (as array()
simply returns the backing array, without taking the offset, position or limit into account).
Another way is to use a utility function (you could make this a static method of a generic utility class if you like):
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;
}
Invoke like so:
byte[] a;
byte[] b;
byte[] result = concat(a, b);
It will also work for concatenating 3, 4, 5 arrays, etc.
Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.
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);
If you prefer ByteBuffer
like @kalefranz, there is always the posibility to concatenate two byte[]
(or even more) in one line, like this:
byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With