Shane Shane - 1 year ago 49
Java Question

Read CSV records while ignoring trailing spaces

I'm iterating through a csv file and pulling out data by the headers. But I want to allow for trailing spaces and still recognize the header.

For example

should still recognized as
Header1 ,Header2,Header3

My code...

final Reader in = new BufferedReader(new InputStreamReader(csv));

for (CSVRecord record : CSVFormat.EXCEL.withHeader().parse(in)) {
try {
final MyObject mo = new MyObject();

But this of course will only find
if it matches exactly (no trailing spaces).

I couldn't find any method like
or something like that

Answer Source

If you store the CSVParser object constructed using CSVFormat.EXCEL.withHeader().parse(in) into a variable, then you can use the method getHeaderMap() to find the indices of the desired headers. These indices can then be used instead of the header names to look up the fields (which is actually also a more efficient way to perform the lookups).

One way to do it is like this:

CSVParser parser = CSVFormat.EXCEL.withHeader().parse(in);
Map<String, Integer> headerMap = parser.getHeaderMap();

int header1Index = -1;
int header2Index = -1;
for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
    String name = entry.getKey();
    int index = entry.getValue();

    switch (name.trim()) {
    case "Header1":
        header1Index = index;
    case "Header2":
        header2Index = index;

for (CSVRecord record : parser) {