Java Scanner.useDelimiter()问题“”

时间:2010-09-30 06:45:11

标签: java java.util.scanner

我遇到了Java Scanner.useDelimiter()分隔符“”的问题。

我正在尝试使用扫描仪读取CSV文件.CSV有2列(名称,描述),描述字段有长段落(带,和。)

我想知道这个案例的分隔符。

3 个答案:

答案 0 :(得分:3)

这样的东西
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]);
}

打印:

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

或者,如果您坚持一直使用扫描仪,您可以执行类似

的操作
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());

(产生相同的输出。)

答案 1 :(得分:2)

只需使用库来读/写像OpenCSV这样的csv,你就不必重新发明轮子了。)

答案 2 :(得分:1)

如果您只有两个以逗号分隔的列,则Scanner的一个简单替代方法就是使用String.substring

int i = s.indexOf(',');
String name = s.substring(0,i);
String desc = s.substring(i+1);