【问题标题】:How to read the contents of a CSV file and put it into a 2D array in Java?如何读取 CSV 文件的内容并将其放入 Java 中的二维数组?
【发布时间】:2021-06-19 17:45:00
【问题描述】:

我只是想问一下如何读取CSV文件的内容并将其放入二维数组中。

我的 CSV 文件的内容每行包含 7 列(以逗号分隔的“,”)。另一方面,行由破折号/连字符“-”分隔。但请注意,这些行仍然在同一行上(它们只是在有分隔 7 列(每行)的破折号/连字符时才被识别。

(CSV 文件中显示的内容是用户输入的,即用户为每行的列输入 7 个值。)

我的问题是,每当用户完成输入第一行的值时,我都会得到一个 java.lang.ArrayIndexOutOfBoundsException: 7 它来自我的二维数组声明的 7 列(我打算在其中插入CSV 文件)在我的 readCustomerCSV 函数中。

函数的具体行是这样的: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++;
        }
    }
}

我的代码中是否有任何遗漏或者我的方法不够好?

【问题讨论】:

  • 我可能是错的,但它看起来像代表新行的破折号,在第 7 个索引(列表中的第 8 个项目)添加到 read2DString 时会触发越界异常(g 会等于 7,这是超出范围的,因为该列表需要第 8 列)。我认为解决方案是先放置 if 语句,然后使用 continue 语句退出该迭代,然后再将其添加到数组以绕过问题。
  • 基本上,您的程序将“-”视为第 8 列,然后再转到下一行。 “第 8 列”将超出范围。
  • 我尝试将声明的 7 更改为 8 但仍然得到一个 ArrayIndexOutOfBounds,特别是它指出 java.lang.ArrayIndexOutOfBoundsException: 8
  • 您还必须使用模运算符 (%) 在每行之后将列重置为 0
  • 哦,好吧,我会使用那个模数运算符,但是我会把它放在代码的哪一部分呢??

标签: java arrays csv multidimensional-array


【解决方案1】:

在将数据解析为 2D 数组之前,您的代码会循环遍历数据的 1D 数组,最终的每一行由破折号分隔。当您进入 for 循环时,您的代码将破折号视为行 read2DString[read2DStringIndex][g] = fromfile[g] 中的第 8 列,因为 g 表示索引 7。只有在此之后,您的代码才会增加该行。为了解决这个问题,您需要将 if 语句放在此行之前,然后使用“继续;”跳到循环的下一个迭代来绕过这个问题。

当您增加行时,您还必须将列重置为 0,而不是 read2DString[read2DStringIndex][g] = fromfile[g] ,使用read2DString[read2DStringIndex][g%8] = fromfile[g]。取模运算符 (%) 将为您提供除法后的余数,在这种情况下,它是在除以已完成行的长度后的正确列号。

【讨论】:

  • 天哪!!!它有效,它没有给出任何越界异常!!!非常感谢@Moshe Goldberg!有事情发生时我会更新你,但再次非常感谢你!!这是修改后的结构,就像我遵循你的概念一样:
  • String [][] read2DString = new String[10][8]; // 把它改成 8 then.. for(int g = 0; g
  • 如果你把它设为 8(而不是 7),你最终会得到一个空的第 8 列。这不会导致错误,但如果您向上移动 if 语句并使用 continue 语句,则没有必要。
  • 哦,好吧,那我就坚持到 7 吧??
  • 是的。虽然想一想,模数应该是 8,而不是 7 (g%8),因为每个新行都在破折号之后开始(新行在 8 个项目之后开始)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多