Easy way to concatenate two byte arrays
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.