Java工具集-Csv文件读取工具类
原创
©著作权归作者所有:来自51CTO博客作者wx5d0241bb88268的原创作品,请联系作者获取转载授权,否则将追究法律责任
添加依赖
<!--开源的opencsv-->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.6</version>
</dependency>
代码示例
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* @program: simple_tools
* @description: Csv文件读取
* @author: Mr.chen
* @create: 2020-04-29 13:53
**/
public class CsvUtil<T> {
public List<T> read(String filePath, Class<T> clazz) {
try {
CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8));
HeaderColumnNameMappingStrategy<T> mapper = new HeaderColumnNameMappingStrategy<>();
mapper.setType(clazz);
return new CsvToBeanBuilder<T>(reader)
.withMappingStrategy(mapper)
.build()
.parse();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(String.format("csv文件: {%s} 读取异常", filePath));
}
return null;
}
}