Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top