话不多说,直接上代码
public static List<Object> ReadCsv(String inpath, Object obj) {
List<Object> list = new ArrayList<Object>(); // 保存读取到的CSV数据
try {
File file = new File(inpath); // 判断文件是否存在
if (!file.exists()) {
logger.info("文件不存在!!!");
} else {
logger.info("获取到文件目录,开始解析");
BufferedReader reader = new BufferedReader(new FileReader(inpath)); // 读取CSV文件
String line = null; // 循环读取每行
while ((line = reader.readLine()) != null) {
String[] row = line.split(",", -1); // 分隔字符串(这里用到转义),CSV大部分都是,或者|来分隔数据的,这里看情况来作决定,存储到List<Object>里
Class clazz = obj.getClass(); // 通过反射获取运行时类
Object infos = clazz.newInstance(); // 创建运行时类的对象
Field[] fs = infos.getClass().getDeclaredFields(); // 得到类中的所有属性集合
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置这些属性值是可以访问的
String type = f.getType().toString(); // 得到此属性的类型
if (type.endsWith("String")) {
f.set(infos, row[i]); // 给属性赋值
}
}
list.add(infos);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
记一次项目中的坑,使用BufferedReader来获取.CSV文件的时候,有时会出现中文乱码的情况,那么就需要对获取到的内容进行一次编码格式的设置,上代码
DataInputStream in = new DataInputStream(new FileInputStream(file));
BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));//解决中文乱码,UTF-8也是可以的