0

I have OpenCSV reader in a Java project and its reading data from CSV files for me, but right now Im hardcoding the number of colums in the loop that reads it. I can recall there was some method that could get the number of columns but I dont remember what it was called and how to use it.

Here is the code:

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;
    }
Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

3 Answers3

2

Just count the items in the array with nextLine.length.

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

Or use a for-each loop:

for (String col : nextLine) {
  list.add(col);
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
0

Well a easy way is that you read the first line with a Scanner of BufferedReader and count the ";" or what you use to split the columns.

You are able to count it if you use

string.toCharArray();

and ++ a Integer if it is ';'.

A second way is the look at the methods of CSV Reader. I don't know them but you can type anywhere in eclipse(don't know how it works in netbeans) "reader." and press control + space. If you have luck there is one.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Gerret
  • 2,948
  • 4
  • 18
  • 28
  • This is a poor answer. Firstly, you suggest that a hand-crafted solution is tried rather than using a library. This is rarely a good idea, especially with CSV parsing. Secondly, you don't provide an actual answer but rather suggest that auto-completion may help. On the whole, not very helpful. – Duncan Jones Aug 12 '13 at 09:33
  • Yes I write this answer because he didnt find a getColumnCount Method. My answer is 100% correct I know that it isnt better than a library. I just want to help so hes able to program. Idk what you mean that I dont provide a answer. It would be work so? The auto completion was a tip from me and not a solution. – Gerret Aug 12 '13 at 09:44
  • You have to be careful counting the delimiters. You also need to take into account that there may be escaped delimiters within the CSV column text. – Razzlero Sep 06 '19 at 04:16
-1

Try this one to get the column count: reader.getColumnCount()

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64