错误:indexoutofbound。读取文件的某些字节时

时间:2012-05-06 10:42:30

标签: android file byte

我想从“offset”读取文件的一些字节,并且它的长度是“大小”。所以我使用FIleInputStream和这段代码:

byte[] data = new byte[size];
FileInputStream fis=new FileInputStream(inputFile);
System.out.println("offset:"+offset+","+"size:"+size);
fis.read(data, offset, size);

所以我有偏移量和大小的真实值,但是接收器错误:indexoutofbound。我不明白。任何人都可以证明我是如何跌倒以及是否有其他正确的方法来做到这一点?

2 个答案:

答案 0 :(得分:1)

JavaDoc告诉你:

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

Throws:
    IndexOutOfBoundsException - If off is negative, len is negative, or len is 
    greater than b.length - off 

请注意索引是从0开始的。

答案 1 :(得分:0)

我不太清楚你在这里offset得到了什么,但是offset意味着你要存储字节的数组中的偏移量(即起始索引)。

因此,您尝试将size字节读入数组,从位置offset开始 - 因此IndexOutOfBounds如果offset > 0。你需要offset为0,它应该可以工作。