[英]How to read the contents of a CSV file and put it into a 2D array in Java?
我只是想問一下如何讀取 CSV 文件的內容並將其放入二維數組中。
我的 CSV 文件的內容每行包含 7 列(以逗號分隔的“,”)。 另一方面,行由破折號/連字符“-”分隔。 但請注意,這些行仍然在同一行上(它們只是在有分隔 7 列(每行)的破折號/連字符時才被識別。
(CSV 文件中出現的內容是用戶輸入的,即用戶為每行的列輸入 7 個值。)
我的問題是,每當用戶完成輸入第一行的值時,我都會得到一個 java.lang.ArrayIndexOutOfBoundsException: 7 來自我的二維數組聲明的 7 列(我計划在其中插入 CSV 文件的值)那在我的 readCustomerCSV 函數中。
function 的具體行是這樣的: read2DString[read2DStringIndex][g] = fromfile[g];
這是我的源代碼:
public void writeCustomerCSV() { // everything in this snippet code works fine(it creates a CSV file which stores the inputs of the user)
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
StringBuilder sb = new StringBuilder();
int y;
for (int x = 0; x < itemTo2D.length; x++) {
for (y = 0; y < itemTo2D[0].length; y++) {
if (itemTo2D[x] != null) {
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
} catch (Exception ex) {
}
}
public void readCustomerCSV() { // reads the contents of the CSV file *having issues with ArrayINdexOutofBounds
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
String[][] read2DString = new String[10][7]; // 2D array where the contents of the CSV file will be inserted (can only get 10 unique values of 7 columns)
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null) {
fromfile = line.split(","); //separates the columns by a comma
}
} catch (Exception ex) {
}
for (int g = 0; g < fromfile.length; g++) {
read2DString[read2DStringIndex][g] = fromfile[g]; // the ArrayIndexOutofBounds is here (inserts the values of the 2D array(by row))
// System.out.print(fromfile[g] + " ");
if (fromfile[g].equals("-")) { //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
}
}
}
我的代碼中是否有任何遺漏或者我的方法不夠好?
在將數據解析為 2D 數組之前,您的代碼會遍歷數據的 1D 數組,每個最終行由破折號分隔。 當您進入 for 循環時,您的代碼將破折號視為read2DString[read2DStringIndex][g] = fromfile[g]
行中的第 8 列,因為 g 表示索引為 7。只有在此之后,您的代碼才會增加排。 為了解決這個問題,您需要將 if 語句放在此行之前,然后使用“繼續;” 跳到循環的下一個迭代來繞過這個問題。
當您增加行時,您還必須將列重置為 0,因此請使用read2DString[read2DStringIndex][g] = fromfile[g]
而不是 read2DString read2DString[read2DStringIndex][g%8] = fromfile[g]
。 模數運算符 (%) 將為您提供除法后的余數,在這種情況下,它是在除以已完成行的長度后的正確列號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.