Java 分割、合并byte数组

时间:2021-03-13 07:14:19

场景:上传文件较大,把存放文件内容byte数组拆分成小的。下载的时候按照顺序合并。

起初觉得挺麻烦的,写完觉得挺简单。

切割:

        /**
* 拆分byte数组
*
* @param bytes
* 要拆分的数组
* @param size
* 要按几个组成一份
* @return
*/
public byte[][] splitBytes(byte[] bytes, int size) {
double splitLength = Double.parseDouble(size + "");
int arrayLength = (int) Math.ceil(bytes.length / splitLength);
byte[][] result = new byte[arrayLength][];
int from, to;
for (int i = 0; i < arrayLength; i++) { from = (int) (i * splitLength);
to = (int) (from + splitLength);
if (to > bytes.length)
to = bytes.length;
result[i] = Arrays.copyOfRange(bytes, from, to);
}
return result;
}

合并: common lang3

ArrayUtils.addAll();