Shane Shane - 2 months ago 7
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

Header1,Header2,Header3
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();
mo.setHeader1(record.get("Header1"));
mo.setHeader2(record.get("Header2"));
mo.setHeader3(record.get("Header3"));
....
}catch(){
....
}
}


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

I couldn't find any method like
record.getIgnoreSpace()
or something like that

Answer

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;
        break;
    case "Header2":
        header2Index = index;
        break;
    }
}

for (CSVRecord record : parser) {
    ...
    mo.setHeader1(record.get(header1Index));
    ...
}
Comments