1、添加依赖
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5.2</version> </dependency>
2、code
public List<GoodsImportParam> readCsv(MultipartFile file, List<GoodsImportParam> badDataList) {
//以","作为解析的分隔符
CSVParser csvParser = new CSVParserBuilder().withSeparator(',').build();
//使用try(){}catch()这种语法资源会自动关闭不需要自己finally里关闭资源,推荐使用
try (
InputStream inputStream = file.getInputStream();
InputStreamReader is = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(is);
CSVReader readerCsv = new CSVReaderBuilder(br).withCSVParser(csvParser).withSkipLines(1).build()) {
String lines[]=null;
List<GoodsImportParam> result = Lists.newArrayList();
while ((lines = readerCsv.readNext()) != null) {
GoodsImportParam data=convertAndCheck(lines,badDataList);
if(null!=data) {
result.add(data);
}
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private GoodsImportParam convertAndCheck(String[] lines, List<GoodsImportParam> badDataList) {
GoodsImportParam importParam = new GoodsImportParam();
Field[] list = GoodsImportParam.class.getDeclaredFields();
for (int i = 0; i < END_DATA_ROW; i++) {
try {
if(checkParam(list[i],lines[i],importParam)) {
list[i].setAccessible(Boolean.TRUE);
list[i].set(importParam, lines[i]);
}else{
importParam =convert(lines,importParam);
badDataList.add(importParam);
return null;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return importParam;
}
private GoodsImportParam convert(String[] lines, GoodsImportParam importParam) {
Field[] list = GoodsImportParam.class.getDeclaredFields();
for (int i = 0; i < END_DATA_ROW; i++) {
list[i].setAccessible(Boolean.TRUE);
try {
list[i].set(importParam, lines[i]);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return importParam;
}
/**
* 参数判断
* @param field
* @param line
* @param importParam
* @return
*/
private boolean checkParam(Field field, String line, GoodsImportParam importParam) {
Annotation notNull= field.getAnnotation(lombok.NonNull .class);
boolean flag=true;
if(notNull!=null&& StringUtils.isBlank(line)){
field.setAccessible(Boolean.TRUE);
ColName colNameAnnotation= field.getAnnotation(com.yinfan.tneko.annotation.ColName.class);
String colName=colNameAnnotation.name();
importParam.setErrorMess(colName+CAN_NOT_EMPTY);
flag=Boolean.FALSE;
}
if(field.getName().equals("cflagStr")&&!ISORNO.contains(line)){
importParam.setErrorMess(ISORNO_ERROR+line);
flag=Boolean.FALSE;
}
if(field.getName().equals("pcs")&&!isNumeric(line)){
importParam.setErrorMess(NOT_NUMBER);
flag=Boolean.FALSE;
}
return flag;
}
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
3、写入
/**
* 写数据
*/
public static void writeCsv(List<GoodsImportParam> datasParam, String myPath) {
List<String[]> datas=covertToWriter(datasParam);
//将内容输入到文件
try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(Paths.get(myPath), StandardCharsets.UTF_8),
CSVWriter.DEFAULT_SEPARATOR,
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END)) {
//写数据到文件
writer.writeAll(datas);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<String[]> covertToWriter(List<GoodsImportParam> datasParam) {
List<String[]> list=Lists.newArrayList();
datasParam.forEach(one->{
String[] vals=new String[10];
Field[] listFiled = GoodsImportParam.class.getDeclaredFields();
for (int i = 0; i < END_DATA_ROW_BACK; i++) {
listFiled[i].setAccessible(Boolean.TRUE);
try {
if(null!=listFiled[i].get(one)) {
vals[i] = listFiled[i].get(one).toString();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
list.add(vals);
});
return list;
}