How to Append/Concat Multiple Byte Arrays in Java

Published May 1, 2022  ∙  Updated May 2, 2022

How can we append a byte array to another byte array?

In other words, how can we concatenate two byte arrays?

Concat using ByteArrayOutputStream

We can write multiple byte arrays into a ByteArrayOutputStream and convert it to a byte array using toByteArray().

private byte[] concatByteArrays(byte[] a, byte[] b) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  return bos.toByteArray();

When performance or memory consumption is of issue, we can specify the buffer capacity in the constructor.

new ByteArrayOutputStream(a.length + b.length);

Additionally, if we want to append a third byte array later on, we can simply write the same instance of ByteArrayOutputStream.


Although, we would have to ensure our ByteArrayOutputStream bos is instantiated outside the utility function we have above.

Concat using System.arraycopy()

We can also use System.arraycopy() to populate our byte array.

private byte[] concatByteArrays(byte[] a, byte[] b) {
  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);
  return c;

The first and second arguments specify the source array and the starting position in that array to copy over, respectively.

The third and fourth arguments specify the destination array and the starting position in that array to receive the copied bytes, respectively.

The final, fifth argument specifies the number of elements to be copied over.

Using Guava’s Bytes.concat()

If we’re using Guava, we can use the library’s Bytes.concat().

This method takes in a variable number of arguments, meaning we can pass in 2 or 50 byte arrays to concatenate.

byte[] c = Bytes.concat(a, b);