This post will discuss how to concatenate two or more byte arrays in Java.

1. Using ByteArrayOutputStream

The recommended solution to concatenate two or more byte arrays is using ByteArrayOutputStream. The idea is to write bytes from each of the byte arrays to the output stream, and then call toByteArray() to get the current contents of the output stream as a byte array.

Download  Run Code

Output:

HelloWorld

 
To concatenate multiple byte arrays, you can write a custom utility method that takes varargs, as shown below:

Download  Run Code

Output:

Hello, World

2. Using System.arraycopy() method

Another elegant solution is to make two calls to System.arraycopy(), which can efficiently copy contents of an array to the destination array. Here’s the complete code:

Download  Run Code

Output:

HelloWorld

 
To concatenate multiple byte arrays, you can create a utility method that takes varargs, as shown below:

Download  Run Code

Output:

Hello, World

3. Using Guava

Guava Bytes class provides several static utility methods pertaining to byte primitives. To concatenate multiple byte arrays, you can use the Bytes.concat() method, which can take any number of arrays.

Download Code

Output:

Hello, World

4. Using Apache Commons Lang Library

Apache Commons Lang also provides static utility methods pertaining to byte primitives. One such method is ArrayUtils.addAll(), which can join two arrays and is overloaded to accept any type.

Download Code

Output:

HelloWorld

5. Using ByteBuffer

The ByteBuffer class in Java, as the name suggests, is a byte buffer. You can use its put() method to transfer contiguous sequences of bytes from a byte array into the buffer, and the array() method to return the byte array that backs this buffer.

Download  Run Code

Output:

HelloWorld

 
The put() method returns the buffer upon which it is invoked. This allows successive method invocations to be chained:

Download  Run Code

Output:

HelloWorld

 
To concatenate multiple byte arrays, you can create a static utility method that takes varargs, as shown below:

Download  Run Code

Output:

Hello, World

That’s all about concatenate two or more byte arrays in Java.