我正在尝试使用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);
}
当我运行它时,它表示没有为标头映射找到类。您是否知道Person.class或映射是否有问题?您能提供的任何帮助将不胜感激。
最佳答案
如果有人遇到此问题,则上面的代码可以正常工作。我的类路径中没有opencsv所需的apache commons lang3。添加完这些后,一切都会开始正常运行。
谢谢
缺口