java - 将 CSV 文件转换为 2D 数组 Java

标签 java arrays csv multidimensional-array

我在 java 中将 CSV 文件转换为 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 复制到第一个字符串数组时,但我不能确定。该文件有 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(","))); 

Create ArrayList from array解释如何将元素数组添加到 arrayList。

关于java - 将 CSV 文件转换为 2D 数组 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15103153/

相关文章:

php - 通过ajax将多个数组传递给javascript

c++ - vector 是否比堆数组更严格地检查越界?

java - 为什么我在 Scriptella 中的输出 CSV 文件上得到双引号?

python - 将 csv 文件加载到 numpy 并按名称访问列

javascript - 使用循环处理 javascript 中的 json 数组

python - 循环使用 csv 文件行中的数字

java - 在 Spring MVC 应用程序中打开静态文件

java - 如何在java中对List中的map进行排序

java - 定制@Scheduled Spring

java - 银行类OOP接口(interface)决定