public class Person {
@CsvBindByName(column = "性别")
private String sex;
@CsvBindByName(column = "姓名")
private String name;
@CsvBindByName(column = "编号")
private String id;
}
//省略getter和setter方法
@Test
public void testHeaderColumn() throws IOException {
String fileName = "D:\\app\\share\\eaglewood-client\\download\\20190605\\testofTab.csv";
InputStreamReader is = new InputStreamReader(CsvUtil.getInputStream(new FileInputStream(fileName)), "utf-8");
HeaderColumnNameMappingStrategy<Person> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(Person.class);
CsvToBean<Person> build = new CsvToBeanBuilder<Person>(is).withMappingStrategy(mappingStrategy).withSeparator(',').build();
List<Person> personList = build.parse();
for(Person person:personList){
System.out.println(person);
}
}
/**
* 读取流中前面的字符,看是否有bom,如果有bom,将bom头先读掉丢弃
* (opencsv 按列名获取bean对象,第一列缺失的情况)
* InputStreamReader is = new InputStreamReader(
* CsvUtil.getInputStream(new FileInputStream(fileName)), "utf-8");
* @param in
* @return
* @throws IOException
*/
public static InputStream getInputStream(InputStream in) throws IOException {
PushbackInputStream testin = new PushbackInputStream(in);
int ch = testin.read();
if (ch != 0xEF) {
testin.unread(ch);
} else if ((ch = testin.read()) != 0xBB) {
testin.unread(ch);
testin.unread(0xef);
} else if ((ch = testin.read()) != 0xBF) {
throw new IOException("错误的UTF-8格式文件");
} else {
}
return testin;
}
csv文件处理——Opencsv
おすすめ
転載: blog.csdn.net/janet1100/article/details/111824611
おすすめ
ランキング