OpenCSV - 如何将选定的列映射到Java Bean,无论顺序如何?(OpenCSV - How to map selected columns to Java Bean regardless of order?)

1041 IT屋

我有一个CSV文件,其中包含以下列: id , fname , , lname ,地址。

我有一个 Person class with id , fname 和 lname 数据成员。我只想将这些列映射到CSV文件中的 Person 对象,并丢弃电话和地址列。我如何做到这一点?解决方案必须扩展,因为将来会添加更多的列。应该工作,不管列位置。



您可以使用 HeaderColumnNameTranslateMappingStrategy 。假设您的CSV包含以下列: Id , Fname ,电话, Lname ,地址。

  CsvToBean< Person> csvToBean = new CsvToBean< Person>(); 

Map< String,String> columnMapping = new HashMap< String,String>();

HeaderColumnNameTranslateMappingStrategy< Person> strategy = new HeaderColumnNameTranslateMappingStrategy< Person>();

列表< Person> list = null;
CSVReader reader = new CSVReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("test.csv")));
list = csvToBean.parse(strategy,reader);

columnMapping将使用 Person 对象。

I have a CSV file with the following columns: id, fname, telephone, lname, address.

I have a Person class with id, fname and lname data members. I want to map only these columns to Person object from a CSV file and discard telephone and address columns. How can I do this? The solution must scale as more columns are added in future. And should work regardless of column position.

In an ideal solution user will only specify columns to read and it should just work.


You can use HeaderColumnNameTranslateMappingStrategy. Lets assume your CSV has the following columns: Id, Fname, Telephone, Lname, Address for the sake of simplicity.

CsvToBean<Person> csvToBean = new CsvToBean<Person>();

Map<String, String> columnMapping = new HashMap<String, String>();
columnMapping.put("Id", "id");
columnMapping.put("Fname", "fname");
columnMapping.put("Lname", "lname");

HeaderColumnNameTranslateMappingStrategy<Person> strategy = new HeaderColumnNameTranslateMappingStrategy<Person>();

List<Person> list = null;
CSVReader reader = new CSVReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("test.csv")));
list = csvToBean.parse(strategy, reader);

The columnMapping will map the columns with your Person object.

本文地址:IT屋 » OpenCSV - 如何将选定的列映射到Java Bean,无论顺序如何?