Easy way to concatenate two byte arrays

androidGuy picture androidGuy · Apr 1, 2011 · Viewed 261.2k times · Source

What is the easy way to concatenate two byte arrays?

Say,

byte a[];
byte b[];

How do I concatenate two byte arrays and store it in another byte array?

Answer

Kevin picture Kevin · Feb 3, 2012

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( );