Reputation: 997
In Java, I am doing some work with RandomAccessFile. I have a file that is 8192 bytes, or 8kb.
The following is causing an ArrayIndexOutOfBoundsException:
File file = new File("TestFile1");
raf = new RandomAccessFile(file, "rw");
byte[] temp = new byte[4096];
raf.read(temp, 4096, 4096);
Even something like this causes the same error:
raf.read(temp, 4096, 1);
Though something like this works perfectly:
raf.read(temp, 0, 4096);
When I run the following, I get 8192, which is why I am confused as to why this is not working:
System.out.println(raf.getChannel().size());
Why am I getting an out of bounds error if I try to read from the second half of the file?
Upvotes: 2
Views: 827
Reputation: 5973
Instead of:
raf.getBytes(temp,4096,4096);
it sounds like you want:
raf.seek(4096); raf.getBytes(temp,0,4096);
The second parameter of getBytes
gives the offset into the buffer into which the content will be read, not the offset into the file.
Upvotes: 7