循环遍历byte[]通过System.arraycopy实现
因为我需要封装一段完整的数据流通过netty-websocket发送服务端进行语音识别操作。
websocket中传送的对象是ByteBuf,因为没有现成的方法将ArrayList<byte[]>对象转换成ByteBuf,所以我尝试先将ArrayList<byte[]>转换成byte[],这样再通过Unpooled.wrappedBuffer(byte[])就可以转换成我想要的ByteBuf对象了。好了思路有了,代码怼上!
//需要处理的是一个ArrayList<byte[]> bytes
int lengthByte = 0;
for(byte[] by : bytes){
lengthByte +=by.length;
}
byte[] allbyte = new byte[lengthByte];
int countLength=0;
for(byte[] by : bytes){
System.arraycopy(by,0,allbyte,countLength,by.length);
countLength+=by.length;
}
// 现在得到的allbyte对象就是拼接完成的byte[]
//参考练手代码 注意 自己使用时要根据自己输入的参数类型进行代码设计!
private static byte[] byteMerger(byte[]... byteList) {
int lengthByte = 0;
for (int i = 0; i < byteList.length; i++) {
lengthByte += byteList[i].length;
}
byte[] allByte = new byte[lengthByte];
int countLength = 0;
for (int i = 0; i < byteList.length; i++) {
byte[] b = byteList[i];
System.arraycopy(b, 0, allByte, countLength, b.length);
countLength += b.length;
}
return allByte;
}