5

I am using a RandomAccessFile in Java 6 but having some strange behavior when reading bytes.

With the following code, where offset and data are appropriately initialized:

int offset;
byte data[];
randFile.readFully(data, offset, data.length);

I get the following stack trace:

null
java.lang.IndexOutOfBoundsException
    at java.io.RandomAccessFile.readBytes(Native Method)
    at java.io.RandomAccessFile.read(RandomAccessFile.java:355)
    at java.io.RandomAccessFile.readFully(RandomAccessFile.java:414)

BUT, with the same values of offset and data, the following (seemingly identical) code works fine!

randFile.seek(offset);

for (int i = 0; i < (data.length); i += 1) {
    data[i] = randFile.readByte();
}

Does anybody have insight into why this might be?

jaynp
  • 3,275
  • 4
  • 30
  • 43

1 Answers1

7

Just guessing, but you probably have an offset greater than 0; if you're reading data.length bytes starting from a position greater than 0, you'll pass the end of the data array, which may be throwing the IndexOutOfBoundsException.

So, if you want to read the full array, offset variable should be set to 0. Besides, if you don't want to start from 0, you should read data.length - offset bytes.-

randFile.readFully(data, offset, data.length - offset);
ssantos
  • 16,001
  • 7
  • 50
  • 70
  • 1
    I think you're correct. I misunderstood the offset parameter as an offset of the file pointer. But the documentation states that data is read from the current file pointer. – jaynp Sep 22 '13 at 18:56
  • If that was finally the issue, please, consider upvoting/accepting answer, it may useful for other users. – ssantos Sep 22 '13 at 19:05
  • 1
    Had the same exact problem here! Totally misinterpreted the documentation and thought that offset was in the file. – waylonion Jan 08 '18 at 03:46
  • @wayway Glad it helped :) – ssantos Jan 08 '18 at 09:47