接上篇SpringBoot项目CSV文件NIO读取_思维穿梭的博客-CSDN博客
在CsvReaderBuilder类中添加类读取方法:
public <T> List<T> toClassRead(T cla) {
if (inputStream == null){
return new ArrayList<>();
}
if (rowNo < 0 ) {
setRowNo(defaultRowNo);
}
List<String> rowList = new ArrayList<>();
listener.setFileLength(fileLength);
readFile();
listener.doAfter();
List<T> list = new LinkedList<>();
Class clazz = cla.getClass();
try {
Constructor declaredConstructor = clazz.getDeclaredConstructor();
Field[] declaredFields = clazz.getDeclaredFields();
for (Object row: listener.getList().subList(rowNo, listener.getList().size())) {
T o = (T) declaredConstructor.newInstance();
List<Object> rowStr = (List<Object>)row;
int size = rowStr.size();
boolean noValue = true;
for (Field field: declaredFields) {
CsvProperty csvProperty = field.getDeclaredAnnotation(CsvProperty.class);
if (null == csvProperty){
continue;
}
Object value = null;
int index = csvProperty.index();
if (index < size){
value = rowStr.get(index);
}
noValue = noValue && (value ==null);
field.setAccessible(true);
field.set(o, value);
}
// 过滤空行
if (noValue){
continue;
}
list.add(o);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
对应的注解:
import java.lang.annotation.*;
/**
* @author 四维穿梭
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CsvProperty {
String value() default "";
int index() default -1;
}
对应的读取文件所要的实体类:
import com.ufc.dream.commons.csv.CsvProperty;
import lombok.Data;
@Data
public class TestBean {
@CsvProperty(index = 0)
private String zone;
@CsvProperty(index = 1)
private String name;
@CsvProperty(index = 2)
private String start;
@CsvProperty(index = 3)
private String end;
@CsvProperty(index = 4)
private String length;
}
使用方式():
public static void testToBean(){
File file = new File("F:\\考勤\\csvFile.csv");
try {
FileInputStream inputStream = new FileInputStream(file);
List<TestBean> objects = CsvReader
.read()
.setRowNo(1)
.setInputStream(inputStream)
.setFileLength(file.length()).setHead(new ArrayList<>())
.toClassRead(new TestBean());
System.out.println(objects.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}