使用supercsv CsvBeanWriter将值写入csv文件。
样本类:
public class Employee {
private String name;
private int empId;
List<String> phoneNumbers;
}
我得到的输出是:
name,empId,phoneNumbers
vijay,1,"[123, 456]"
请注意List<String> phoneNumbers
[]
我的问题是如何使用supercsv将其读回Employee类(bean)。
我尝试使用CsvBeanReader
&amp; CsvDozerBeanReader
但无法阅读List<String>
。
我得到了非法的例外。 感谢任何指针!
完整代码:
public class DozerBeanReader {
public static void main(String [] args){
ICsvDozerBeanReader beanReader = null;
try {
beanReader = new CsvDozerBeanReader(new FileReader("Employee.csv"),
CsvPreference.STANDARD_PREFERENCE);
String [] header = beanReader.getHeader(true); // ignore the header
Class<?> [] hintTypes = {String.class, Integer.class, List.class};
beanReader.configureBeanMapping(Employee.class, header, hintTypes);
Employee readEmp1 = beanReader.read(Employee.class);
readEmp1.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您依赖于以下事实:List
个电话号码使用列表的toString()
格式编写为单个CSV列,例如[123, 456]
。
您将收到类似以下内容的异常:
org.dozer.MappingException: Illegal object type
for the method 'setPhoneNumbers'.
Expected types:
java.util.List
Actual types:
java.lang.String
因为Dozer不知道如何将字符串[123, 456]
转换为List
。您可以执行此操作,但您需要编写cell processor以将该字符串转换回List
。如果你的电话号码是纯粹的数字,不应该太难,但如果你的电话号码有逗号,那么事情就会变得混乱!
我建议将每个电话号码编写为一个单独的列 - 它使得它变得更加容易(对于任何阅读文件的人,包括你!)。
您需要做的就是将CsvDozerBeanReader和CsvDozerBeanWriter与indexed mapping一起使用。
这是一个例子 - 关键部分是索引映射:
String[] fieldMapping = new String[] { "name",
"empId", "phoneNumbers[0]", "phoneNumbers[1]" };
示例:
// create employee to write/read
Employee employee = new Employee();
employee.setEmpId(1234);
employee.setName("Vijay");
employee.setPhoneNumbers(Arrays.asList("123", "456"));
// the CSV header
String[] header = new String[] { "name",
"empId", "phoneNumber1", "phoneNumber2" };
// the field mapping
String[] fieldMapping = new String[] { "name",
"empId", "phoneNumbers[0]", "phoneNumbers[1]" };
// write the employee
StringWriter out = new StringWriter();
ICsvDozerBeanWriter writer =
new CsvDozerBeanWriter(out,
CsvPreference.STANDARD_PREFERENCE);
writer.configureBeanMapping(Employee.class, fieldMapping);
writer.writeHeader(header);
writer.write(employee);
writer.flush();
// read the employee
ICsvDozerBeanReader reader =
new CsvDozerBeanReader(new StringReader(out.toString()),
CsvPreference.STANDARD_PREFERENCE);
reader.configureBeanMapping(Employee.class, fieldMapping);
reader.getHeader(true); // ignore header
Employee e = reader.read(Employee.class);
System.out.println(e);
假设您已编写toString()
方法,则应打印
Employee [name=Vijay, empId=1234, phoneNumbers=[123, 456]]