2

Currently, I am using this tutorial on how to read CSV file: https://stackabuse.com/reading-and-writing-csvs-in-java-with-apache-commons-csv/ It used CSVParser and CSVFormat from Apache-commons-csv.

It can read perfectly fine but not in a way that I want. After I check the reason on why it doesn't work turns out that my CSV file has the separator of "|" instead of "," and CSVParser can't read it. Is there a way for me to change the separator for CSVParser to "|" instead of ","? I really want to use this method since record.get("name of the map") really helps me a lot with this project that I am doing and I don't want to change the CSV file manually.

This is my current code:

@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");
        }
    }

Any kind of help is appreciated.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Gagak
  • 129
  • 2
  • 13

1 Answers1

2

Did you try using

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

See http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withDelimiter-char- for related JavaDoc.

centic
  • 15,565
  • 9
  • 68
  • 125
  • This is now deprecated as stated in the doc, and this should be used instead: https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.Builder.html#setDelimiter-char- – ACV Jul 13 '22 at 11:10