繁体   English   中英

尝试从文件中读取某些字节时,为什么会超出索引范围?

[英]Why am I getting an index out of bounds when I try to read certain bytes from a file?

谁能弄清楚为什么我在这里超出索引范围? 我可以读取第一批数据,但是当我尝试再次循环执行此操作时会出错。 我还在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++;
}

看一下这个电话:

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

这时候,很好offset是0 -但如果它不是 0,你问读512个字节到一个数组里面只有512个字节长,但在数组的开头启动-因此没有足够的空间,所有512个字节您所要求的。

我怀疑您想要:

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

...或者可替代地,仅将offset保留为0。目前尚不清楚RRQ.doRRQ功能,但是您没有传递offset令人怀疑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM