在Java中合并多个byte数组
在Java中合并多个byte数组有几种常见的方法,下面我将介绍几种实现方式:
方法1:使用System.arraycopy()
public static byte[] mergeByteArrays(byte[]... arrays) {
// 计算总长度
int totalLength = 0;
for (byte[] array : arrays) {
totalLength += array.length;
}
// 创建新数组
byte[] result = new byte[totalLength];
// 复制各个数组到结果数组
int offset = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
方法2:使用ByteArrayOutputStream
import java.io.ByteArrayOutputStream;
public static byte[] mergeByteArraysWithStream(byte[]... arrays) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (byte[] array : arrays) {
outputStream.write(array, 0, array.length);
}
return outputStream.toByteArray();
}
方法3:使用Java 8 Streams
import java.util.Arrays;
public static byte[] mergeByteArraysWithStream(byte[]... arrays) {
return Arrays.stream(arrays)
.flatMapToInt(Arrays::stream)
.collect(() -> new byte[0], (result, value) -> {
byte[] newResult = new byte[result.length + 1];
System.arraycopy(result, 0, newResult, 0, result.length);
newResult[result.length] = (byte) value;
result = newResult;
}, (left, right) -> {
byte[] newResult = new byte[left.length + right.length];
System.arraycopy(left, 0, newResult, 0, left.length);
System.arraycopy(right, 0, newResult, left.length, right.length);
left = newResult;
});
}
方法4:使用Apache Commons IO
如果你可以使用第三方库,Apache Commons IO提供了更简洁的方法:
import org.apache.commons.io.IOUtils;
public static byte[] mergeWithCommonsIO(byte[]... arrays) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (byte[] array : arrays) {
IOUtils.write(array, outputStream);
}
return outputStream.toByteArray();
}
性能比较
- System.arraycopy() - 性能最好,直接操作内存
- ByteArrayOutputStream - 代码简洁,性能较好
- Java 8 Streams - 代码简洁但性能较差
- Apache Commons IO - 代码最简洁,但需要引入第三方库
使用示例
public static void main(String[] args) {
byte[] array1 = {1, 2, 3};
byte[] array2 = {4, 5, 6};
byte[] array3 = {7, 8, 9};
byte[] merged = mergeByteArrays(array1, array2, array3);
System.out.println(Arrays.toString(merged)); // 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
}
选择哪种方法取决于你的具体需求,如果性能是关键因素,推荐使用System.arraycopy()方法。
