Java Scanner.useDelimiter() problem with ""
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开发者_Go百科 long paragraphs (with , and .)
I am wondering what delimiter for this case.
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.)
Just use a library for reading/writing csv like OpenCSV and you don't have to reinvent the wheel :)
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);
精彩评论