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.
-
try this, https://stackoverflow.com/questions/23057761/parsing-a-csv-file-with-custom-string-separator – Arun Prasat Jun 22 '21 at 03:32
2 Answers
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.

- 76
- 3
-
I want to specify the delimiter as a string not char, the example you gave is of "-" char. I want to use the String "|%|". Thanks again for your help. – naveed1224 Jun 23 '21 at 01:31
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();
…

- 1