JAVA: InputStream.read中的字节数组分配(byte[] b, int off, int len)

JAVA: Byte array allocation in InputStream.read(byte[] b, int off, int len)

我有一个大文件,我想从中获取分成 20,000,000 字节块的字节。

我写了这样一段代码:

File clipFile = new File("/home/adam/Temp/TheClip.mp4");
InputStream clipIStream = new FileInputStream(clipFile);

long chunkSize = 20000000;

long fileSize = clipFile.length();
long totalParts = (long) Math.ceil(fileSize / chunkSize);

for(int part=0; part < totalParts; part++) {
    long startOffset = chunkSize * part;
    byte[] bytes = new byte[(int)chunkSize];
    clipIStream.read(bytes, (int) startOffset, (int) chunkSize));

    // Code for processing the bytes array
    // ...
}

程序在第一次迭代后崩溃,生成 IndexOutOfBoundsException

经过查阅the documentation发现如下:

public int read(byte[] b, int off, int len) throws IOException

(...)

The first byte read is stored into element b[off], the next one into b[off+1], and so on.

这意味着,在第二次迭代时 read 开始写入位置 bytes[20000000],而不是我想要的 bytes[0]。

有什么方法可以实现每次迭代都在字节数组的开头写入字节吗?

不要将 startOffset 传递给 the read method

off - the start offset in array b at which the data is written.

偏移量在数组中,而不是在流中。改为传递 0,从数组的开头开始写入。