mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
Fix (hutool-core): 修复拆分byte数组为几个等份时最后一组长度不足 len 时依旧按照 len 分配导致读取过多额外数据的问题
# 修改 1. 在原有实现中,不论最后一组数据有多少都会按照 len 来分配空间,如果最后一组数据长度小于 len 但是又按照 len 的长度分配空间的话就会出现很多无意义的数据,为了保持数据的干净,改为在最后一组时按照剩余数据长度分配空间,确保不会填充无意义的数据。 2. 修改了变量的名称,使得更容易理解变量的意义。 3. 修改了计算等份数量的实现,因为余数必然比 len 小,所以如果出现余数必然是只加 1 的,因此去除原有的专门记录额外长度的 z 变量,当有余数的时候直接在等份数量上加 1 即可。 4. 增加了测试方法用于验证修改是否正确
This commit is contained in:
parent
6fc58999b8
commit
70503136f1
@ -520,26 +520,26 @@ public class PrimitiveArrayUtil {
|
||||
// ---------------------------------------------------------------------- split
|
||||
|
||||
/**
|
||||
* 拆分byte数组为几个等份(最后一份可能小于len)
|
||||
* 拆分byte数组为几个等份(最后一份按照剩余长度分配空间)
|
||||
*
|
||||
* @param array 数组
|
||||
* @param len 每个小节的长度
|
||||
* @return 拆分后的数组
|
||||
*/
|
||||
public static byte[][] split(byte[] array, int len) {
|
||||
int x = array.length / len;
|
||||
int y = array.length % len;
|
||||
int z = 0;
|
||||
if (y != 0) {
|
||||
z = 1;
|
||||
int amount = array.length / len;
|
||||
int remainder = array.length % len;
|
||||
if (remainder != 0) {
|
||||
++amount;
|
||||
}
|
||||
byte[][] arrays = new byte[x + z][];
|
||||
byte[][] arrays = new byte[amount][];
|
||||
byte[] arr;
|
||||
for (int i = 0; i < x + z; i++) {
|
||||
arr = new byte[len];
|
||||
if (i == x + z - 1 && y != 0) {
|
||||
System.arraycopy(array, i * len, arr, 0, y);
|
||||
for (int i = 0; i < amount; i++) {
|
||||
if (i == amount - 1 && remainder != 0) {
|
||||
arr = new byte[remainder];
|
||||
System.arraycopy(array, i * len, arr, 0, remainder);
|
||||
} else {
|
||||
arr = new byte[len];
|
||||
System.arraycopy(array, i * len, arr, 0, len);
|
||||
}
|
||||
arrays[i] = arr;
|
||||
|
@ -424,4 +424,12 @@ public class ArrayUtilTest {
|
||||
Assert.assertTrue(o instanceof Integer);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void splitTest() {
|
||||
byte[] array = new byte[1024];
|
||||
byte[][] arrayAfterSplit = ArrayUtil.split(array, 500);
|
||||
Assert.assertEquals(3, arrayAfterSplit.length);
|
||||
Assert.assertEquals(24, arrayAfterSplit[2].length);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user