繁体   English   中英

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

在查阅文档之后我发现了以下内容:

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

(......)

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

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

是否有任何方法可以在每次迭代时在字节数组的开头写入字节?

不要将startOffset传递read方法

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM