Combines multiple byte arrays into a single, longer byte array. - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Combines multiple byte arrays into a single, longer byte array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] a = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(java.util.Arrays.toString(combineArrays(a)));
    }/*from   ww  w .ja  v a2  s. co m*/

    /**
     * Combines multiple byte arrays into a single, longer byte array. Each byte array is appended to the end of the previous byte
     * array. The arrays do not need to be the same length. An example: [1, 2, 3] and [4, 5] and [6, 7, 8, 9] would return the byte
     * array of [1, 2, 3, 4, 5, 6, 7, 8, 9].
     * @param a - The byte arrays to combine.
     * @return The combined byte array.
     */
    public static byte[] combineArrays(byte[]... a) {
        int massLength = 0;
        for (byte[] b : a)
            massLength += b.length;
        byte[] c = new byte[massLength];
        byte[] d;
        int index = 0;
        for (int i = 0; i < a.length; i++) {
            d = a[i];
            for (int j = 0; j < d.length; j++)
                c[j + index] = d[j];
            index += d.length;
        }
        return c;
    }
}

Related Tutorials