The problem you have it that each iteration calls iterator(), which returns a NEW Iterator .
Things are getting weird past this point, since the iterator has a current field storing the current record, and of course the current record of a new iterator is null .
In that case it calls getNextRecord() from CSVParser (source code), thus skipping a line .
If you want to stick with the iterator, just re-use the same instance :
Iterator<CSVRecord> iterator = parser.iterator();
while(iterator.hasNext()) {
console.log(iterator.next().get(0).trim());
}
Answer from Arnaud on Stack OverflowThe problem you have it that each iteration calls iterator(), which returns a NEW Iterator .
Things are getting weird past this point, since the iterator has a current field storing the current record, and of course the current record of a new iterator is null .
In that case it calls getNextRecord() from CSVParser (source code), thus skipping a line .
If you want to stick with the iterator, just re-use the same instance :
Iterator<CSVRecord> iterator = parser.iterator();
while(iterator.hasNext()) {
console.log(iterator.next().get(0).trim());
}
Well, by default, the parser considers the first line as the header (column definition), so it is skipped in the returned records. To include this line, you must prepare your formatting accordingly, using withSkipHeaderRecord.
EDIT: Sorry, I've read too fast. I thought only first line was skipped.
You can simply iterate over the resulting records and access the i-th item of a record via record.get(i), e.g.
Reader in = new StringReader(
"DAR_123451 ,\"XXXXX Hello World Hello World XXX \"\n" +
"DAR_123452 ,\"XXXXX Hello World Hello World XXX \"");
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
for (CSVRecord record : records) {
for (int i = 0; i < record.size(); i++) {
System.out.println("At " + i + ": " + record.get(i));
}
}
You can access the column names (keys and values) of a CSVRecord by doing:
private void printRecords(final CSVParser csvRecords) {
for (CSVRecord csvRecord : csvRecords) {
for (Entry<String, String> column : csvRecord.toMap().entrySet()) {
System.out.println(column.getKey() + "=" + column.getValue());
}
}
}
Alternatively you can iterate over CSVRecord in the same way like over java.util.ArrayList.