tags:

views:

61

answers:

3

Hi all,

I have having a problem with Java Scanner.useDelimiter() delimiting "".

I am trying to use the Scanner to read a CSV file.The CSV have 2 column (Name, Description) and the Description field have long paragraphs (with , and .)

I am wondering what delimiter for this case.

+3  A: 

How about something like

Scanner s = new Scanner("name1 lorem, some description\n" +
                        "name2 ipsum, some other, description \n" +
                        "name3 dolor, a third. description\n");

while (s.hasNextLine()) {
    String[] cols = s.nextLine().split(",", 2); // limit to two columns.
    System.out.println("col1: " + cols[0] + ", col2:" + cols[1]);
}

Prints:

col1: name1 lorem, col2: some description
col1: name2 ipsum, col2: some other, description 
col1: name3 dolor, col2: a third. description

Alternatively, if you insist on using Scanner all the way, you could do something like

Scanner s = new Scanner("name1 lorem, some description\n" +
                        "name2 ipsum, some other, description \n" +
                        "name3 dolor, a third. description\n");

s.useDelimiter(",");

while (s.hasNext())
    System.out.println("col1: " + s.next() + ", col2:" + s.skip(",").nextLine());

(Which yields the same output.)

aioobe
+1  A: 

If you've only got two columns, separated by a comma, an easy alternative to Scanner is to just use String.substring:

int i = s.indexOf(',');
String name = s.substring(0,i);
String desc = s.substring(i+1);
dogbane
or String.split
Thilo
+2  A: 

Just use a library for reading/writing csv like OpenCSV and you don't have to reinvent the wheel :)

willcodejavaforfood
That will also take care of quoted quotes and commas within a field and multi-line strings and so on.
Thilo