I have a csv file with headers in order fname,mname,lname and a csv parser to parse this. I am reading the file line by line and splitting by delimitter (",") and according to index i'll get the values 0=fname, 1=mname, 2=lname.
Now again if a csv comes with headers in the order lname,fname and mname i have to change the code again. I want to write a generic parser which regardless of the order of the header stores the value in respective fields. Any suggestions?
I suggest not to write a generic parser and use Apache Commons CSV .
As you don't know the order of the columns, use CSVFormat as described in its documentation:
Referencing columns safely
If your source contains a header record, you can simplify your code and safely reference columns, by using withHeader(String...) with no arguments:
CSVFormat.EXCEL.withHeader();
This causes the parser to read the first record and use its values as column names. Then, call one of the CSVRecord get method that takes a String column name argument:
String value = record.get("Col1");
This makes your code impervious to changes in column order in the CSV file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.