java 8 将字节分割成块

Abh*_*hal 2 java split file java-8 java-stream

我必须创建一个方法,需要将文件分成多个字节。

示例 byte[] 到 List<byte[]> 中,假设每个大小为 1 MB (sizeMB=1 * 1024 * 1024)

因此 5.2 MB 文件应该由五​​个 1MB 和一个 2KB 组成。[2kb、1MB、1MB、1MB、1MB、1MB]。

byte[] mainFile=getFIle();
List<bute[]> listofSplitBytes=getFileChunks(mainFile);

public void list<bute[]> getFileChunks(byte[] mainFile) {
    int sizeMB = 1 * 1024 * 1024;
    // Split the files logic
}
Run Code Online (Sandbox Code Playgroud)

我试图避免添加if then else来处理。我正在尝试寻找是否有更干净的方法来做到这一点,例如使用流或类似的东西?

ETO*_*ETO 6

尝试这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

或者如果您想要一个实用的解决方案,请尝试以下操作:

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());
}
Run Code Online (Sandbox Code Playgroud)