2

I can't understand the core of apache commons csv library. Could you advice a method I should use when I want to get columns by header name from csv file by apache-commons-csv? For example, I have such csv file:

Delays, Computation time, Communication time
0., 500000, 10
20., 563210, 20
55., 546541., 23.
12., 465487., 23.
45., 456547., 28.
87., 985458., 56.
47., 456778., 45.

I want to get arrays: double[] delays, double[] compTime, double[] commTime consist of values from csv.

Kenenbek Arzymatov
  • 8,439
  • 19
  • 58
  • 109

2 Answers2

1
public void parseInputCSV() throws IOException {
final Reader reader = new InputStreamReader(inputFile.toURL().openStream(), "UTF-8");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);
for (CSVRecord record : records) {
    String first = record.get("FIRST_COLUMN");
    String second = record.get("SECOND_COLUMN");
    // all other columns
}

}

Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
0

In the documentation :

Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
  String lastName = record.get("Last Name");
  String firstName = record.get("First Name");
}

You'll get for each row the cell corresponding to the column name. (here lastName and firstName are not used and are deleted at each iteration, sure).

Aeldred
  • 314
  • 2
  • 15
  • Just algorithm here, take 3 arrays, for each row, add cells to their array.... This is not apache commons here. Just an algorithm. – Aeldred Apr 04 '16 at 13:16