public List<byte[]> getFileChunks(byte[] mainFile) {
int sizeMB = 1 * 1024 * 1024;
List<byte[]> chunks = new ArrayList<>();
for (int i = 0; i < mainFile.length; ) {
byte[] chunk = new byte[Math.min(sizeMB, mainFile.length - i)];
for (int j = 0; j < chunk.length; j++, i++) {
chunk[j] = mainFile[i];
}
chunks.add(chunk);
}
return chunks;
}
or if you want a functional solution, then try this:
public List<byte[]> getFileChunks(byte[] mainFile) {
final int sizeMB = 1 * 1024 * 1024;
return IntStream.iterate(0, i -> i + sizeMB)
.limit((mainFile.length + sizeMB - 1) / sizeMB)
.mapToObj(i -> Arrays.copyOfRange(mainFile, i, Math.min(i + sizeMB, mainFile.length)))
.collect(Collectors.toList());
}
or
public
static
byte
[][] divideArray(
byte
[] source,
int
chunksize) {
byte
[][] ret =
new
byte
[(
int
)Math.ceil(source.length / (
double
)chunksize)][chunksize];
int
start =
0
;
for
(
int
i =
0
; i < ret.length; i++) {
ret[i] = Arrays.copyOfRange(source,start, start + chunksize);
start += chunksize ;
}
return
ret;
}