0

我在 Java 项目中有 OpenCSV 阅读器,它为我从 CSV 文件中读取数据,但现在我对读取它的循环中的列数进行硬编码。我记得有一些方法可以获取列数,但我不记得它叫什么以及如何使用它。

这是代码:

public ArrayList<ArrayList<String>> getCSVContent(String filepath) throws Exception {
        CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
        ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            ArrayList<String> list = new ArrayList<String>();
            for (int i = 0; i < 5; i++) { //5 is the number of columns in the file 
                list.add(nextLine[i]);
            }
            array.add(list);
        }
        reader.close();
        return array;
    }
4

3 回答 3

2

只需用 . 计算数组中的项目nextLine.length

for (int i = 0; i < nextLine.length; i++) { 
  list.add(nextLine[i]);
}

或者使用 for-each 循环:

for (String col : nextLine) {
  list.add(col);
}
于 2013-08-12T08:26:42.600 回答
0

一个简单的方法是您使用 BufferedReader 的扫描仪读取第一行并计算“;” 或者你用来分割列的东西。

如果您使用,您可以计算它

string.toCharArray();

和 ++ 一个整数,如果它是';'。

第二种方法是查看 CSV Reader 的方法。我不认识他们,但你可以在 eclipse 中的任何地方输入(不知道它在 netbeans 中是如何工作的)“阅读器”。并按控制+空格。如果你有运气,有一个。

于 2013-08-12T08:57:47.393 回答
-1

试试这个来获取列数:reader.getColumnCount()

于 2013-08-12T08:29:08.927 回答