Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java CSV Reader, reading remaining data

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. 1

  2. mm/dd/yy

  3. 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 ?

like image 752
pam Avatar asked Jul 19 '26 01:07

pam


1 Answers

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

like image 153
xiaolei yu Avatar answered Jul 20 '26 15:07

xiaolei yu