MY代码是csv文件并逐行读取并存储到数据库。 如何验证每行数据是否正确。 如果正确读取的所有数据,则仅存储数据库,否则不存储并返回“ csv文件中的正确数据,请检查”。
县名验证应为字符串/仅文本, 国家/地区代码验证应仅是数字,最多4个数字
这是我的代码,无需任何验证即可正常工作
@PostMapping(value = {"/upload-csv"})
public ResponseEntity<?> CreateCountrytBulk(@RequestParam("file") MultipartFile inputFile, @RequestParam("type") Integer type) {
BufferedReader crunchifyBuffer = null;
String workingDir = System.getProperty("user.dir") +"/csv/";
if (!inputFile.isEmpty()) try {
byte[] bytes = inputFile.getBytes();
Path path = Paths.get(workingDir + inputFile.getOriginalFilename());
Files.write(path, bytes);
countryCodeMapRepository.deleteAll();
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(workingDir+ inputFile.getOriginalFilename()));
String[] line;
while ((line = reader.readNext()) != null) {
String y = line[0];
String country_name=y.trim();
String x = line[1];
Integer country_id = Integer.valueOf(x);
CountryCodeMapEntity countryCodeMapEntity = new CountryCodeMapEntity();
if(!(country_name ==null)&&!(country_id ==null)) {
countryCodeMapEntity.setCountry_name(country_name);
countryCodeMapEntity.setCountry_id(country_id);
countryCodeMapEntity.setStatus(1);
countryCodeMapEntity.setCreatedBy(1);
countryCodeMapEntity.setCreatedOn(LocalDateTime.now());
countryCodeMapRepository.save(countryCodeMapEntity);
}else{
return ResponseEntity.ok(new ApiResponse(false, "County List some value missing", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(new ApiResponse(true, "County List created successfully", ""));
} catch (Exception e) {
return ResponseEntity.ok(new ApiResponse(true, "County List created successfully", ""));
}
else {
return ResponseEntity.ok(new ApiResponse(true, "County List created successfully", ""));
}
}