I have CSV data as following:
1,mm/dd/yy,"abc,def,"pqr",xyz"
I would like to have this parsed into 3 strings.
1
mm/dd/yy
all remaining data, in this case, "abc,def,"pqr",xyz"
I have tried several libraries, openCSV, javacsv etc. all of them seems to parse and tokenize last column as well. What I want is remaining data after second column as a single token.
Any ideas ?
You should update the input data to enclose the 3rd column with single quote, like the following: 1,mm/dd/yy,'abc,def,"pqr",xyz'
Otherwise, you will never resolve the csv data correctly.
With the updated data, you can call the powerful open source library uniVocity-parsers to read the data correctly in just several lines:
public static void main(String[] args) throws FileNotFoundException {
// 1st, config the CSV reader
CsvParserSettings settings = new CsvParserSettings();
settings.getFormat().setLineSeparator("\n");
settings.getFormat().setQuote('\''); // set the quote to single quote '
settings.getFormat().setQuoteEscape('\\'); // escape the double quote "
// 2nd, creates a CSV parser with the configs
CsvParser parser = new CsvParser(settings);
// 3rd, parses all rows from the CSV file into a 2-dimensional array
List<String[]> resolvedData = parser.parseAll(new StringReader("1,mm/dd/yy,'abc,def,\"pqr\",xyz'"));
for (String[] row : resolvedData) {
StringBuilder strBuilder = new StringBuilder();
for (String col : row) {
strBuilder.append(col).append("\t");
}
System.out.println(strBuilder);
}
}
And you will get output like this:
1 mm/dd/yy abc,def,"pqr",xyz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With