參考資料: opencsv文檔
寫下本文時(shí)最新版的opencsv版本為4.0, maven坐標(biāo)如下:
<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文件對(duì)應(yīng)的java bean
public class TestBean {
// 通過屬性名綁定csv列名, 屬性名必須與csv列名相同
@CsvBindByName
private Integer id;
// 解析Date格式
@CsvBindByName
@CsvDate("yyyy-MM-dd")
private Date date;
// csv列名與字段名不同時(shí)
@CsvBindByName(column = "name")
private String name;
// csv不存在列名時(shí)也可通過位置綁定, 如 `@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);
}
}
結(jié)果中中文顯示亂碼
[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無法指定字符編碼, 此時(shí)應(yīng)當(dāng)使用InputStreamReader設(shè)置字符編碼
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);
}
}
從結(jié)果來看, 中文解析以及正常了
[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=啊]]
實(shí)際上csv列名為中文時(shí), 只要在bean中對(duì)應(yīng)屬性配置了@CsvBindByName(column = "中文列名")
也是可以解析的