上传csv文件并解析

思路:先将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("上传文件失败,请重新上传!");
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码厚炮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值