Monday 27 November 2023

Concatenates the byte arrays in Java

Following snippet concatenates the byte arrays in Java.

public static byte[] concat(byte[]... byteArrays) {

	try {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		for (byte[] byteArray : byteArrays) {

			if (byteArray == null) {
				continue;
			}

			baos.write(byteArray);
		}
		return baos.toByteArray();

	} catch (IOException e) {
		throw new IllegalStateException(e.getMessage(), e);
	}
}

Above snippet defines a method ‘concat’ that combines multiple byte arrays into a single byte array. It uses a ByteArrayOutputStream to store the concatenated byte arrays. The method checks for null byte arrays and skips them. For non-null byte arrays, it writes their content to the ByteArrayOutputStream. After processing all input byte arrays, the content of the ByteArrayOutputStream is converted into a single byte array, which is then returned.

 

Find the below working application.

 

ByteArrayConcatenation.java

package com.sample.app;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayConcatenation {

	public static byte[] concat(byte[]... byteArrays) {

		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			for (byte[] byteArray : byteArrays) {

				if (byteArray == null) {
					continue;
				}

				baos.write(byteArray);
			}
			return baos.toByteArray();

		} catch (IOException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	public static void main(String[] args) {
		byte[] arr1 = { 2, 3, 5, 7 };
		byte[] arr2 = { 23, 25, 27, 29 };
		byte[] arr3 = { 33, 35, 37, 39 };

		byte[] concatenatedArray = concat(arr1, arr2, arr3);
		
		System.out.println("Elements in the concatenated array are : ");
		for(byte b : concatenatedArray) {
			System.out.println(b);
		}

	}

}

Output

Elements in the concatenated array are : 
2
3
5
7
23
25
27
29
33
35
37
39




You may like

Interview Questions

Array programs in Java

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

Convert a wrapper array to primitive array in Java

No comments:

Post a Comment