-1

is there any way to parse CSV file (variable number of columns) with the help of some CSV parser (e.g. SuperCSV) to set of List<String> without skipping quotes in Java? For the input:

id,name,text,sth
1,"John","Text with 'c,o,m,m,a,s' and \"",qwerty
2,Bob,"",,sth

after parsing, I'd like to have in the set the same text as in input instead of:

id,name,text,sth
1,John,Text with 'c,o,m,m,a,s' and \",qwerty
2,Bob,null,null,sth

that element

"John" will parsed to string "John" ( instead of John )

"" --> ""

,, --> ,null,

etc.

I already wrote about this here, but I probably didn't make this clear enough. I want to parse csv file to set of List<String>, do something with this and print to the stdout leaving quotes where they was. Please help me.

Community
  • 1
  • 1
user3521479
  • 565
  • 1
  • 5
  • 12
  • possible duplicate of [CSV parser in JAVA, double quotes in string (SuperCSV, OpenCSV)](http://stackoverflow.com/questions/23000676/csv-parser-in-java-double-quotes-in-string-supercsv-opencsv) – Raedwald Apr 11 '14 at 12:02
  • 1
    Clarify you original question, rather than asking it again but in different words. – Raedwald Apr 11 '14 at 12:02

2 Answers2

0

Something like this? Not using any existing parser, doing it from scratch:

public List<String> parse(String st) {

    List<String> result = new ArrayList<String>();

    boolean inText = false;
    StringBuilder token = new StringBuilder();
    char prevCh = 0;
    for (int i = 0; i < st.length(); i++) {
        char ch = st.charAt(i);
        if (ch == ',' && !inText) {
            result.add(token.toString());
            token = new StringBuilder();
            continue;
        }
        if (ch == '"' && inText) {
            if (prevCh == '\\') {
                token.deleteCharAt(token.length() - 1);
            } else {
                inText = false;                    
            }
        } else if (ch == '"' && !inText) {
                inText = true;
        }
        token.append(ch);
        prevCh = ch;
    }
    result.add(token.toString());
    return result;
}

Then

String st = "1,\"John\",\"Text with 'c,o,m,m,a,s' and \\\"\",qwerty";

List<String> result = parse(st);
System.out.println(result);

Will print out:

[1, "John", "Text with 'c,o,m,m,a,s' and "", qwerty]
Udo Klimaschewski
  • 5,150
  • 1
  • 28
  • 41
0

I have used this one: http://opencsv.sourceforge.net/

And I was pretty satasfied with the results. I had a bunch of differently organized CSV files (it's sometimes funny what kinds of things people call CSV these days), and I managed to set up the reader for it. However, I don't think it will generate commas, but it will leave blanks where there is an empty field. Since you can fetch the whole line as an array, you can iterate it and but a comma between each iteration.

Look up the settings, there is a bunch of them, including quote characters.

Aleksandar Stojadinovic
  • 4,851
  • 1
  • 34
  • 56