I have a input file whose delimiter is a combination of characters like #$#. But apache commons CSVParser consider only a character not multiple characters. Please find the input file:
Rajeev Kumar Singh ♥#$#[email protected]#$#+91-9999999999#$#India
Sachin Tendulkar#$#[email protected]#$#+91-9999999998#$#India
Barak Obama#$#[email protected]#$#+1-1111111111#$#United States
Donald Trump#$#[email protected]#$#+1-2222222222#$#United States
Code snippet:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CSVReader {
private static final String SAMPLE_CSV_FILE_PATH = "./users.csv";
public static void main(String[] args) throws IOException {
try (
Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL.withDelimiter('#'))
) {
long recordCount;
List<CSVRecord> csvRecords = csvParser.getRecords();
}
}
}
Please help me in using delimiter with multiple characters in above example, delimiter is only a single character which is ‘#’. I need to set the delimiter as ‘#$#’.
3
Answers
I am not quite clear why use
CSVParser
in your case. I just tested it locally with your data and come up with this parsing demo:The output will be:
By the way, the csv.txt is in the
resources
:The buffering now is done twice, one could use other Reader/FileInputStream and such.