如何组合两个字节数组

nov*_*rmr 60 java

我有两个字节数组,我想知道如何将一个添加到另一个或组合它们以形成一个新的字节数组.

pic*_*ypg 103

你只是想连接两个字节数组?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);
Run Code Online (Sandbox Code Playgroud)

或者您可以使用List来完成工作:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);
Run Code Online (Sandbox Code Playgroud)

  • 或者您可以使用System.arraycopy() (7认同)
  • 好决定。我从未见过“System.arraycopy();” (2认同)
  • 您不能将“list.toArray(new byte[list.size()])”与原始类型一起使用。相反,它应该是“Byte[]组合= list.toArray(new Byte[list.size()])” (2认同)

小智 23

您可以使用Apace common lang package(org.apache.commons.lang.ArrayUtilsclass)来完成此操作.您需要执行以下操作

byte[] concatBytes = ArrayUtils.addAll(one,two);
Run Code Online (Sandbox Code Playgroud)

  • 您对开销的恐惧让我认为您在执行此循环时都会因 UI 冻结而受到困扰。也许您应该考虑“AsyncTask”(android),这是阻止循环中断 UI 线程的唯一方法。 (2认同)

小智 7

我认为这是最好的方法,

public static byte[] addAll(final byte[] array1, byte[] array2) {
    byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    return joinedArray;
}
Run Code Online (Sandbox Code Playgroud)