Reputation: 621
Can anyone figure out why I'm getting an index out of bounds exception here? I can read in the first lot of data but when I try and loop this again it errors. Im also getting an 'assigned value is never used' error on the is.read(readBytes, offset, length); part of this too.
InetAddress address = packet.getAddress();
int port = packet.getPort();
RRQ RRQ = new RRQ();
int offset = 0;
int length = 512;
int block = 0;
byte[] readBytes = new byte[512];
File file = new File(filename);
FileInputStream is = new FileInputStream(file);
int fileBytes = is.read(readBytes, offset, length);
DatagramPacket outPacket = RRQ.doRRQ(readBytes, block, address, port);
socket.send(outPacket);
block++;
if (fileBytes != -1)
{
socket.receive(packet);
offset = offset + fileBytes;
System.out.println(offset);
Exceptions here:fileBytes = is.read(readBytes, offset, length);
outPacket = RRQ.doRRQ(readBytes, block, address, port);
socket.send(outPacket);
block++;
}
Upvotes: 0
Views: 4343
Reputation: 1500615
Look at this call:
fileBytes = is.read(readBytes, offset, length);
That's fine when offset
is 0 - but when it's not 0, you're asking to read 512 bytes into an array which is only 512 bytes long, but not starting at the beginning of the array - therefore there's not enough room for all 512 bytes that you've asked for.
I suspect you want:
fileBytes = is.read(readBytes, offset, length - offset);
... or alternatively, just leave offset as 0. It's not clear what RRQ.doRRQ
does, but it's suspicious that you don't pass in offset
...
Upvotes: 11