2

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?

1
  • 1
    a quick hack way, you read the header to to an Arraylist<String> read the line by line .. when you look for fname , get the index of it from the arraylist then you will know the index of the stored data. Agian that's just a hack. Personally create yourself an object for each Line with the appropriate headers as your deal with each line . Commented Jun 12, 2015 at 10:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I went through this, but i think even in this we have to declare the CSVFormat first i mean the order of headers. I dont want to declare this as i dont know in which order the fields will come. I only know what fields. Any other option?
CSVFormat precisely allows you to reference columns without knowing their order. See my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.