'Java library to read csv and sppecify custom delimiter more than 1 char(string) "|%|"

Need to read a csv file with custom string delimiter for example "|%|". Currently I am using CSV commons library, but it only allows splitting by char and not string. I would prefer splitting by sticking to CSV commons library, but open to other libraries as well.



Solution 1:[1]

If the CSV file uses a different delimiter, and not the default delimiter (which is a comma), it is easy to configure the CSVFormat to handle it. Say the file is delimited with a hyphen:

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CSVReaderWithDifferentDelimiter {
    public static void main(String[] args) throws IOException {
        String csvFilePath = "../csvFileWithDiffDelimiter.csv";

        Reader reader = Files.newBufferedReader(Paths.get(csvFilePath));
        CSVFormat csvFormat = CSVFormat.newFormat('-')
                .withFirstRecordAsHeader();

        CSVParser csvParser = csvFormat.parse(reader);
        csvParser.getRecords()
                .forEach(csvRecord -> System.out.println(csvRecord.toMap()));
    }
}

Note that we are not using the DEFAULT CSVFormat anymore and are constructing one from scratch. We pass the delimiter as the new format method argument. The rest of the configuration like record separator, escape sequence etc will default.

Solution 2:[2]

You need to read a CSV file by the user-defined delimiter (a string instead of a character). It is roundabout to do this in Java. But it is very simple to get this done using SPL, an open-source Java package. Only one line of code is enough:

A
1 =file("custom.csv").import@t(;,"|%|")

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as readcsv.splx and invoke it in Java as you call a stored procedure:

…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st=con.prepareCall("call readcsv ()");
st.execute();
…

Or execute the SPL string within a Java program as we execute a SQL statement:

…
st = con.prepareStatement("==file(\"custom.csv\").import@t (;,\"|%|\")");
st.execute();
…

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 troy
Solution 2 JinJune