[英]JAVA: Byte array allocation in InputStream.read(byte[] b, int off, int len)
I have a big file from which I want to get bytes divided in 20,000,000 bytes chunks. 我有一个大文件,希望从该文件中将字节分成20,000,000字节的块。
I wrote a code like this: 我写了这样的代码:
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
// ...
}
The program crashes after the first iteration, generating IndexOutOfBoundsException
. 程序在第一次迭代后崩溃,生成
IndexOutOfBoundsException
。
After consulting the documentation I found the following: 在查阅文档之后,我发现了以下内容:
public int read(byte[] b, int off, int len) throws IOException
public int read(byte [] b,int off,int len)抛出IOException
(...)
(......)
The first byte read is stored into element b[off], the next one into b[off+1], and so on.
读取的第一个字节存储在元素b [off]中,下一个字节存储在b [off + 1]中,依此类推。
It means, that on second iteration read
begins writing on position bytes[20000000], instead of bytes[0] as I would want it. 这意味着,在第二次迭代中,
read
开始在位置byte [20000000]上写入,而不是我想要的bytes [0]。
Is there any way to achieve writing bytes on the beginning of the bytes array on every iteration? 是否有任何方法可以在每次迭代时在字节数组的开头写入字节?
Don't pass startOffset
into the read
method . 不要将
startOffset
传递给read
方法 。
off - the start offset in array b at which the data is written.
off-数组b中写入数据的起始偏移量。
The offset is into the array, not into the stream. 偏移量在数组中,而不在流中。 Pass
0
instead, to write from the beginning of the array. 而是传递
0
,以从数组的开头开始写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.