参考资料: opencsv文档
写下本文时最新版的opencsv版本为4.0, maven坐标如下:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.0</version>
</dependency>
测试用test.csv
id,date,name
1,2017-10-11,amy
2,2017-10-12,啊
与csv文件对应的java bean
public class TestBean {
// 通过属性名绑定csv列名, 属性名必须与csv列名相同
@CsvBindByName
private Integer id;
// 解析Date格式
@CsvBindByName
@CsvDate("yyyy-MM-dd")
private Date date;
// csv列名与字段名不同时
@CsvBindByName(column = "name")
private String name;
// csv不存在列名时也可通过位置绑定, 如 `@CsvBindByPosition(position = 0) `
// getter, setter and toString() ...
}
使用opencsv解析
public class CsvParser {
public static void main(String[] args) throws IOException {
String path = "test.csv";
List<TestBean> beans = new CsvToBeanBuilder<TestBean>(new FileReader(path))
.withType(TestBean.class).build().parse();
System.out.println(beans);
}
}
结果中中文显示乱码
[TestBean [id=1, date=Wed Oct 11 00:00:00 CST 2017, name=amy],
TestBean [id=2, date=Thu Oct 12 00:00:00 CST 2017, name=��]]
由于FileReader无法指定字符编码, 此时应当使用InputStreamReader设置字符编码
public class CsvParser {
public static void main(String[] args) throws IllegalStateException, IOException {
String path = "test.csv";
String charset = "utf-8";
FileInputStream fileInputStream = new FileInputStream(path);
Reader reader = new InputStreamReader(fileInputStream, charset);
List<TestBean> beans = new CsvToBeanBuilder<TestBean>(reader)
.withType(TestBean.class).build().parse();
System.out.println(beans);
}
}
从结果来看, 中文解析以及正常了
[TestBean [id=1, date=Wed Oct 11 00:00:00 CST 2017, name=amy],
TestBean [id=2, date=Thu Oct 12 00:00:00 CST 2017, name=啊]]
实际上csv列名为中文时, 只要在bean中对应属性配置了@CsvBindByName(column = "中文列名")
也是可以解析的