问题
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:
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.
来源:https://stackoverflow.com/questions/35594121/how-to-validate-the-csv-headers-using-opencsv