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];
}
或者你可以使用 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);
或者你可以使用 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()]);
byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);
当然,这可以处理两个以上的汇总,并使用一个在代码中定义的连接字符集:
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;
或者,以更简单的形式,没有这个字符:
byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");
但是你需要抑制 UnsupportedEncodingException,这是不太可能被抛出。
最快的方法:
public static byte[] concat(byte[] a, byte[] b) {
int lenA = a.length;
int lenB = b.length;
byte[] c = Arrays.copyOf(a, lenA + lenB);
System.arraycopy(b, 0, c, lenA, lenB);
return c;
}