下面的代碼被設計爲需要一個字節[]和其他一些東西(請參閱它給出的代碼)。然後它建立一定長度的數據包並返回。我的問題是,當我在一個文件中讀入主程序時,我需要數據報數據包的緩衝區爲剩餘字節數(如果小於512)+4。這是處理讀取請求的最後一個數據包的TFTP服務器。我在索引「buffer [bufferOffset] = data [dataOffset];」獲得一個索引越界異常。任何人都可以幫助我理解爲什麼會發生這種情況,最好的解決辦法是什麼?IndexOutOfBounds - 需要幫助
public DatagramPacket doRRQ(byte[] data, int block, InetAddress address, int port, long fileSize, long sentBytes){
//takes file data and creates a buffer for a DATA packet to be used in a RRQ. This packet
//is passed to MyFirstTFTPServer.java to be modified and sent to client. This is done
int bufferOffset = 3;
int dataOffset = -1;
byte[] buffer = null;
long difference = 0;
int i = 512;
byte byteBlock = (byte)block++;//possible issue with block no increment. test.
if (sentBytes + 512 > fileSize){
difference = fileSize - sentBytes;
difference = difference + 4;
i = (int)difference;
buffer = new byte[i];
} else {
buffer = new byte[516];
}
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
buffer[0] = 0;
buffer[1] = 3;
buffer[2] = 0;
buffer[3] = byteBlock;
for(byte item:data){
bufferOffset++;
dataOffset++;
buffer[bufferOffset] = data[dataOffset];
//System.out.println(bufferOffset);
//System.out.println(dataOffset);
}
return packet;
}
請發佈整個異常消息。至少要提及哪一個數組是破... – thkala
三個字母:jdb – Kevin
線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:223.它還聲明異常在RRQ.doRRQ()的第49行(這是我在上面的帖子中提到的那一行)。不會給出打破陣列的名稱。我懷疑它的緩衝區,但是它具有可變長度。並且程序只在最後一個數據包上出現錯誤 – DMo