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

标签 java file byte arrays inputstream

我有一个大文件,我想从中获取分成 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/

相关文章:

java - 'before ApplicationContext'阶段没有触发应用事件

java - Java字符串中是否有像Python中的 '%r'这样的格式说明符?

java - SWT UI 线程没有响应 - 打印错误

c - 帮助结构(段错误)

c# - 保存图像文件和节省内存的最佳方式

c++ - 设置一个字节等于一个 int 和 cout

python - 如何在Python中将16位无符号整数拆分为字节数组?

java 创建一个类方法来搜索数组的字长

java - 从 servlet 内部调用 java 方法

function - 向预先存在的结构添加功能