如何在java中连接字节数组

时间:2015-07-10 08:44:37

标签: java arrays

在Java中连接两个字节数组的简单方法是什么? 我使用了这个函数但是出了错误:

  

java.lang.ArrayIndexOutOfBoundsException:16

我的功能是:

public static byte[] concatinate(byte[] a, byte[] b) {
    byte[] c = new byte[100];
    for (int i = 0; i < (a.length + b.length); i++) {
        if (i < a.length) {
            c[i] = a[i];
        } else {
            c[i] = b[i];
        }
    }
    return c;
}

3 个答案:

答案 0 :(得分:5)

首先,如果a.length + b.length > 100,您的代码绑定将失败。您应该使用a.length + b.length作为c的长度。

是的,因为当你过去a.length时,你仍然在尝试使用b[i]。想象一下a.length是50而b.length是1.你有51个数组元素要填充,但要填充c [50]你需要b [0],而不是b [50]。

您需要改变的是:

c[i] = b[i];

对此:

c[i] = b[i - a.length];
根据Mureinik的回答,

......或者有两个循环。 (我不希望任何一个选项明显快于另一个选项,它们肯定是等价的 - 你可以使用你认为最具可读性的选项。)

但是,我建议改为使用System.arraycopy

public static byte[] concatenate(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;
}

更简单:)

答案 1 :(得分:1)

只需将数组定义为组合的两个数组的大小,并逐个迭代

public static byte[] concatinate(byte[] a, byte[] b) {
    byte[] c = new byte[a.length + b.length];
    for (int i = 0; i < a.length; i++) {
        c[i] = a[i];
    }

    for (int i = 0; i < b.length; i++) {
        c[a.length + i] = b[i];
    }

    return c;
}

答案 2 :(得分:1)

附加2字节[]的代码很好。如果你想继续附加byte [],你可以使用这段代码....

byte [] readBytes; //你的字节数组.... //例如。 readBytes =&#34; TestBytes&#34; .getBytes();

ByteArrayBuffer mReadBuffer = new ByteArrayBuffer(0); //而不是0,如果你知道预期字节数的计数,那么很高兴在这里输入

mReadBuffer.append(readBytes,0,readBytes.length); //这会将readBytes字节数组中的所有字节复制到mReadBuffer中 // readBytes的任何新条目,您可以通过重复相同的调用来附加此处。

//最后,如果你想把结果变成byte []形式: byte [] result = mReadBuffer.buffer();