How to concatenate byte array in java with an easy example

In this Java tutorial, We will learn how easily we can concatenate multiple byte array in Java. That’s mean you can concatenate two or more byte array in Java easily.

In order to do this, we will first create some byte arrays and then we will create another byte array which will be used to concatenate all the byte arrays created before.

You can concatenate byte arrays in Java with two easy ways,

  1. Using the Class ByteBuffer.
  2. or you can also use ByteArrayOutputStream

Happy New Year JavaScript Web Script to Share on Whatsapp with Countdown

Concatenate Multiple Byte Array in Java using ByteArrayOutputStream

Take a look at this below code:

import java.io.*;
public class MyClass {
   public static void main(String args[]) throws IOException {
      byte[] my_first_byte_array = { 87,45,98};
      byte[] my_another_byte_array = { 74,54,8};
      byte[] my_new_byte_array = { 75,12,89};
      ByteArrayOutputStream my_stream = new ByteArrayOutputStream();
      my_stream.write(my_first_byte_array);
      my_stream.write(my_another_byte_array);
      my_stream.write(my_new_byte_array);
      byte[] concatenated_byte_array = my_stream.toByteArray();     // Byte arrays are concatenated now

       // you can use these below for loop to print the new concatenated byte array (if you wish)
      for(int a=0; a< concatenated_byte_array.length ; a++) {
         System.out.print(concatenated_byte_array[a] +" ");
      }
   }
}

Output:

87 45 98 74 54 8 75 12 89

Concatenate Multiple Byte Array in Java using ByteBuffer

I personally like this one because of ” It is an inbuilt method, it is simple enough and it can also concatenate large byte arrays too “

Here is a code snippet for the learners:

byte[] first_array = { } // put some elements in it separated by commas
byte[] another_array = { } // put some elements in it separated by commas
ByteBuffer final_array = ByteBuffer.wrap(bigByteArray);
final_array.put(first_array);
final_array.put(another_array);

That’s all.

I hope these examples gonna help you. If you have any doubts or questions please feel free to put that in the below comment section provided below.

You can also read,

One response to “How to concatenate byte array in java with an easy example”

  1. a says:

    bigByteArray what it is?
    could it be empty?
    more details needed for tis example

Leave a Reply

Your email address will not be published. Required fields are marked *