我在寫一段從.txt文件中讀取數據並將其存儲在二維數組中的Java代碼。對於某些文件,代碼工作得很好,但對於其他文件,它會拋出ArrayIndexOutOfBoundsException,儘管據我所知,該數組有足夠的空間!雖然有足夠的空間可用,但數組索引超出範圍
下面的代碼:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ExtractData {
static String[][] data;
static String line;
static int amountOfEntries;
static int amountOfSeparators;
public static String[][] getData(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename));
System.out.println("Fetching data for file " + filename);
amountOfEntries = Utilities.countLines(filename);
amountOfSeparators = (Utilities.countOccurencesOfCharacter(filename, ' ')/amountOfEntries) + 1;
String[] temp = new String[amountOfEntries]; // for extracted data, still needs to be separated
int alpha = 0;
while((line = in.readLine()) != null) {
temp[alpha] = line;
alpha++;
}
in.close();
System.out.println("Done!");
System.out.println("Parsing Data to Cache...");
String[][] parsedData = new String[amountOfEntries][amountOfSeparators];
String[] parts = new String[amountOfSeparators];
for (int i = 0; i < amountOfEntries; i++) {
parts = (temp[i]).split(" ");
for (int k = 0; k < amountOfSeparators; k++) {
parsedData[i][k] = parts[k];
Utilities.debugMethod(filename + "[" + i + "][" + k + "]", parsedData[i][k]);
}
}
System.out.println("Done!");
return parsedData;
}
public static void fetchDataAndParsetoSQL(String filename) throws IOException {
System.out.println("Present working directory: " + System.getProperty("user.dir"));
data = getData(filename);
System.out.println("Creating SQL statements and writing to file...");
String tablename = Utilities.sqltableName(filename);
toSQL.SQLOutput(data, tablename, filename);
System.out.println("Done!");
}
}
我得到的異常就行
parsedData[i][k] = parts[k];
這是非常煩人,我似乎無法在別處找到了答案的問題,特別是因爲即使對文本文件不起作用,它仍然在拋出異常之前正確解析文件的前60行。
任何人都有一個想法可能會導致這種情況?
請顯示確切的異常以及'i'和'k'的值。請注意,您提交的代碼甚至不會編譯,因爲''''不是有效的字符文字。 –
不應該考慮循環條件考慮的部分[]長度? – dly
異常告訴你數組的大小和正在使用的索引值。其中之一不是你所期望的。並且在這裏抱怨錯誤時,總是會引用* entire *和* exact *錯誤信息。 –