首页 > 解决方案 > 有没有办法使用 CSVParser 为 CSV 文件添加自定义分隔符?

问题描述

目前,我正在使用本教程来了解如何读取 CSV 文件:https : //stackabuse.com/reading-and-writing-csvs-in-java-with-apache-commons-csv/ 它使用了 Apache 的 CSVParser 和 CSVFormat-公共-csv。

它可以很好地阅读,但不是我想要的方式。在我检查了它为什么不起作用的原因后发现我的 CSV 文件有分隔符“|” 而不是 "," 并且 CSVParser 无法读取它。有没有办法让我将 CSVParser 的分隔符更改为“|” 代替 ”,”?我真的很想使用这种方法,因为record.get("name of the map")我正在做的这个项目对我有很大帮助,我不想手动更改 CSV 文件。

这是我当前的代码:

@PostMapping("/uploadFile")
    public static void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException{
        if(file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
            InputStreamReader input = new InputStreamReader(file.getInputStream());
            CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
            for (CSVRecord record : csvParser) {
                System.err.println(record.get("nameOftheColumn"));
            }
            response.sendRedirect("/rekonsiliasi");
        }
        else {
            response.sendRedirect("/rekonsiliasi");
        }
    }

任何形式的帮助表示赞赏。

标签: javacsvapache-commons-csv

解决方案


你试过用

CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().withDelimiter('|').parse(input);

有关相关 JavaDoc,请参阅http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withDelimiter-char-


推荐阅读