思路:先将csv文件上传到本地路径后,然后进行读取解析,可删除可不删除
示例代码:
1、上传文件到本地
MultipartFile file = null; //上传的文件,直接从方法参数中获取
if (file == null) {
throw new RuntimeException("文件为空");
}
String fileName = file.getOriginalFilename();
String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if (!".csv".equals(suffixName)) {
throw new RuntimeException("上传文件格式需要是csv文件");
}
FileOutputStream outputStream = null;
InputStream inputStream = null;
String nowDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String batchId = UUID.randomUUID().toString(); //可以加入随机字符串
String uploadFileName = prefixName + "-" + batchId + suffixName; //rename file
String filePath="";//自定义文件存放路径
File f = new File(filePath + File.separator + nowDate + File.separator + uploadFileName);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
try {
outputStream = new FileOutputStream(f);
inputStream = file.getInputStream();
byte[] bytes = new byte[5125];
int i = -1;
while ((i = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, i);
}
outputStream.flush();
log.info("uploadedFile {} ....... success", f.getPath());
return f.getPath();
} catch (Exception e) {
log.error("Upload file fail", e);
throw new RuntimeException("上传数据失败, 请修改后重新上传, " + e.getMessage());
} finally {
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
}
此处采用的文件流是自己捕获异常,关闭输入和输出流的,jdk8中可以直接使用
try()catch{}
,如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便。
2、按指定路径解析csv文件内容,可变换csv表头字段的顺序
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.7</version>
</dependency>
String filePath ="";//上传后的文件全路径
BufferedReader bufferedReader;
try {
InputStreamReader fileReader = new InputStreamReader(new FileInputStream(filePath), "GBK");
bufferedReader = new BufferedReader(fileReader);
} catch (Exception e) {
throw new RuntimeException("read file error!");
}
Iterator<CSVRecord> iterator = null;
try {
iterator = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(bufferedReader).iterator();
} catch (IOException e) {
return Result.fail("format trade file error");
}
int lineCount = 1;
while (iterator.hasNext()) {
try {
lineCount = lineCount + 1; //可以通过记录行数提示哪一行有问题
CSVRecord csvRecord = iterator.next();
Map<String, String> map = csvRecord.toMap();
String userName = map.get("userName"); //可以直接通过map获取文件列
String tradeType = map.get("tradeType");
BigDecimal amount = new BigDecimal(map.get("amount"));
BigDecimal price = new BigDecimal(map.get("price"));
BigDecimal qty = new BigDecimal(map.get("qty"));
BigDecimal fee = new BigDecimal(map.get("fee"));
} catch (Exception e) {
log.error("process trade record file error: {}", e);
return Result.fail("上传文件失败,请重新上传!");
}
}