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

时间:2015-10-06 19:11:28

标签: java file byte bytearray inputstream

我有一个大文件,我想从中获取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)           抛出IOException

     

(...)

     

读取的第一个字节存储在元素b [off]中,下一个存入元素   b [off + 1],依此类推。

这意味着,在第二次迭代read开始写位置字节[20000000],而不是像我希望的那样写入字节[0]。

有没有办法在每次迭代时在bytes数组的开头写字节?

1 个答案:

答案 0 :(得分:4)

不要将startOffset传递给the read method

  

off - 数组b中写入数据的起始偏移量。

偏移量是进入数组,而不进入流。相反,请传递0,从数组的开头写入。

相关问题