0

谁能弄清楚为什么我在这里得到索引越界异常?我可以读入第一批数据,但是当我尝试再次循环时,它会出错。我还在 is.read(readBytes, offset, length); 这也是一部分。

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++;
}
4

1 回答 1

11

看看这个调用:

fileBytes = is.read(readBytes, offset, length);

offset为 0 时很好 - 但当它为 0 时,您要求将 512 个字节读入一个只有 512 个字节长的数组,但不是从数组的开头开始 - 因此没有足够的空间容纳所有 512 个字节你要求的。

我怀疑你想要:

fileBytes = is.read(readBytes, offset, length - offset);

...或者,只需将偏移量保留为 0。目前尚不清楚是什么RRQ.doRRQ,但您不传入是可疑的offset...

于 2012-05-21T18:47:45.243 回答