Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons CSV Mapping not found

I am trying to read a CSV file with certain headers into a Java object using Apache Commons CSV. However, when I run the code, I get the following exeption:

Exception in thread "main" java.lang.IllegalArgumentException: Mapping for Color not found, expected one of [Color, Name, Price, House Cost, Rent, 1 House, 2 Houses, 3 Houses, 4 Houses, Hotel, Mortgage]
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:102)
at GameBoard.<init>(GameBoard.java:25)
at Game.main(Game.java:3)

Can someone explain where the exception is coming from? It appears to me that Apache Commons somehow is not matching my input to a column. Is there something wrong on my part or is something else broken? Here is my code snippet:

Reader in;
    Iterable<CSVRecord> records = null;
    try {
        in = new FileReader(new File(Objects.requireNonNull(getClass().getClassLoader().getResource("Properties.csv")).getFile()));
        records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
    } catch (IOException | NullPointerException e) {
        e.printStackTrace();
        System.exit(1);
    }
    for (CSVRecord record :
            records) {
        spaces.add(new Property(
                record.get("Color"),
                record.get("Name"),
                Integer.parseInt(record.get("Price")),

And here are my csv headers (sorry, one was cut off but that's not the point): csv headers

Thanks!

like image 359
Norman Percy Avatar asked Dec 06 '18 01:12

Norman Percy


2 Answers

I had the same probem which only occurs if you reference the first column, all other column names are working. The problem is, that the UTF-8 representation prepends the following characters "0xEF,0xBB,0xBF" (see Wikipedia page). This seems to be a known problem for commons-csv but since this is application specific, it won't be fixed (CSVFormat.EXCEL.parse should handle byte order marks).

However, there is a documented workaround for this:

http://commons.apache.org/proper/commons-csv/user-guide.html#Handling_Byte_Order_Marks

like image 77
Thorsten Kitz Avatar answered Nov 10 '22 04:11

Thorsten Kitz


I got the same weird exception. It actually said "Expecting one of ..." and then listed the field it said it could not find - just like in your case.

The reason was that I had set the wrong CSVFormat:

CSVFormat csvFormat = CSVFormat.newFormat(';');

This meant that my code was trying to separate fields on semi-colons in a file that actually had comma separators.

Once I used the DEFAULT CSVFormat, everything started to work.

CSVFormat csvFormat = CSVFormat.DEFAULT;

So the answer is that probably you must set CSVFormat correctly for your file.

like image 33
mwarren Avatar answered Nov 10 '22 05:11

mwarren