How to validate the csv headers using opencsv

血红的双手。 提交于 2019-12-24 01:13:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!