[英]Converting CSV file into 2D Array Java
我在將CSV文件轉換為Java中的2D數組時遇到了一些麻煩。 我可能會走最長的路,但似乎無法弄清楚為什么我會出錯。 每一行和每一列應該具有25個元素。 這是我的代碼:
BufferedReader CSVFile = new BufferedReader(new FileReader(fileName));
String dataRow = CSVFile.readLine();
// Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
while (dataRow != null) {
dataRow.split(",");
list.add(dataRow);
dataRow = CSVFile.readLine();
// Read next line of data.
}
// Close the file once all data has been read.
CSVFile.close();
String[] tokens = null;
Object[] test = list.toArray();
String[] stringArray = Arrays.copyOf(test, test.length, String[].class); //copies the object array into a String array
//splits the elements of the array up and stores them into token array
for (int a = 0; a < test.length; a++) {
String temp = stringArray[a];
tokens = temp.split(",");
}
//converts these String tokens into ints
int intarray[] = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
intarray[i] = Integer.parseInt(tokens[i]);
}
//attempts to create a 2d array out of a single dimension array
int array2d[][] = new int[10][3];
for (int i = 0; i < 25; i++) {
for (int j = 0; j < 25; j++) {
array2d[i][j] = intarray[(j * 25) + i];
}
}
我相信錯誤是當ArrayList復制到第一個String數組時,但是我不確定。 該文件有25列25行。 我不斷得到的錯誤是數組在索引25處超出范圍。任何輸入將不勝感激。 謝謝!
for (int a = 0; a < test.length; a++) {
String temp = stringArray[a];
tokens = temp.split(","); //< -- OLD VALUE REPLACED WITH NEW SET OF TOKENS
}
tokens
將僅包含最后使用的字符串的標記, 而不是到目前為止看到的所有標記。 因此tokens.length == 25
和訪問tokens[25]
是ArrayOutOfBounds
異常。
您應該進行以下更改
ArrayList<String> tokens = new ArrayList<String>();
...
tokens.addAll(Arrays.asList(temp.split(",")));
從array創建ArrayList解釋了如何將元素數組添加到arrayList。
順便說一句,做自己的CSV解析可能不是您時間上最有效的使用方式(除非這是家庭作業)。 有很多很棒的庫可以處理這個問題(opencsv,commons-lang3),它們處理諸如引用,空令牌,可配置的分隔符等問題。
這是commons-lang3的示例:
StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
while (...) {
tokenizer.reset(dataLine);
String tokens[] = tokenizer.getTokenArray();
...
}
現在,您可以自由地專注於要對數據進行處理的實際邏輯,而不必進行繁瑣的解析操作。
而且,如果您只想將令牌作為平面列表收集,請執行以下操作:
StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
List<String> allTokens = new ArrayList<String>();
while (...) {
tokenizer.reset(dataLine);
allTokens.addAll(tokenizer.getTokenList());
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.