我有一个大文件,我想从中获取分成 20,000,000 字节 block 的字节。
我写了这样的代码:
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
,从数组的开头写入。
关于JAVA:InputStream.read中的字节数组分配(byte[] b, int off, int len),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32977803/