Merge pull request #1494 from FULaBUla/v5-dev

Fix (hutool-core): 修复拆分byte数组时最后一组长度不足 len 时依旧按照 len 分配空间导致读取过多额外数据的问题
This commit is contained in:
Golden Looly 2021-03-31 08:23:11 +08:00 committed by GitHub
commit ad54b670f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 11 deletions

View File

@ -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;

View File

@ -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);
}
}