gpt4 book ai didi

java - OpenCSV 解析带标题的 CSV 到列表

转载 作者:行者123 更新时间:2023-12-01 11:45:04 29 4
gpt4 key购买 nike

我正在尝试使用 opencsv 3.3 与一些用户解析一个简单的 csv 文件并将其放入 bean 中,但在运行代码时出现类未找到异常。我用于读取对象的 Person.class 文件如下。

public class Person {
private String firstname;
private String lastname;
private String email;
private String type;

/*public Person () {}
public Person (String firstname, String lastname, String email, String type) {
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.type = type;
}*/

//set all the variables for the person
//set the first name
public String getFirstName() {
return firstname;
}
public void setFirstName(String firstname) {
this.firstname = firstname;
}

//set the last name
public String getLastName() {
return lastname;
}
public void setLastName (String lastname) {
this.lastname = lastname;
}

//set the email address of the user
public String setEmail() {
return email;
}
public void getEmail(String email) {
this.email = email;
}

//set the type for the user
public String setType() {
return type;
}
public void getType (String type) {
this.type = type;
}

@Override
public String toString() {
return "User [firstname=" + firstname + ", lastname=" + lastname + ", email=" + email + ", type=" + type + "]";
}
}

读取 csv 的代码如下。

String filename = "D:/Projects/deploy/resources/sample.csv";
try {
HeaderColumnNameTranslateMappingStrategy<Person> strategy = new HeaderColumnNameTranslateMappingStrategy<Person>();
strategy.setType(Person.class);
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("firstname", "firstname");
mapping.put("lastname", "lastname");
mapping.put("email", "email");
mapping.put("type", "type");
strategy.setColumnMapping(mapping);
System.out.println("past the mapping");

CSVReader reader = new CSVReader(new FileReader(filename));
System.out.println("past the reader");

CsvToBean<Person> csvbean = new CsvToBean<Person>();
System.out.println("past the csvtobean");

List<Person> csvusers = csvbean.parse(strategy, reader);
System.out.println(csvusers);


} catch (Exception e) {
System.out.println("there was an exception in the main program:" + e);
}

当我运行它时,它说没有找到用于 header 映射的类。您知道这是 Person.class 还是映射的问题吗?如果您能提供任何帮助,我们将不胜感激。

最佳答案

如果有人遇到这个问题,上面的代码可以正常工作。我的类路径中没有 opencsv 所需的 apache commons lang3 。添加后,一切都开始正常工作。

谢谢尼克

关于java - OpenCSV 解析带标题的 CSV 到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29216168/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com