4

I am using opencsv to parse csv file data which has been uploaded using web and populating the read data in the bean (using HeaderColumnNameTranslateMappingStrategy) which is working fine.

But struggling to find best way to validate (as a first check) that if the file has all the headers before starting processing the data.

Opencsv still process the file and populate null values in the bean when the file does not have all the headers that have been passed as a columnsMapping map.

1 Answer 1

2

So given a CSV file you want to ensure that the header contains a set of required elements before processing.

I would create a utility class with a readHeader method that takes the file name and using the CSVReader read the header using the readNext() as an string array (instead of skipping over it) and returns it.

Then you can add a second method that takes that array and an array or list of required fields and then using something like the Apache Commons ArrayUtils make sure that each element in your required array is in the header array and return true if so, false otherwise.

Then if you want you can create a third method that combines the two to hide the complexity .

Hope that helps.

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

2 Comments

Sure, I can do that but at server side i don't have the file but the inputstream and once I opened the inputstream for verifying the header I won't be able to use existing CsvToBean#parse implementation to parse the data.
Ahhh - streams. Okay there is a way but you have to wait until after the parse (because it is during the parse that the header is read). So the fact that you are using the HeaderColumnNameTranslateMappingStrategy means you have a map of columns - that or you can quickly create a subset of that map for the columns that are required. Once the parse is done you can loop through the names and then call the getColumnIndex method on the HeaderColumnNameTranslateMappingStrategy passing in the real name of the column. As long as you do not get back a null Integer then the column is there.

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.