2010-09-30 47 views
1

我有一個Java Scanner.useDelimiter()分隔「」的問題。Java Scanner.useDelimiter()問題與「」

我試圖用掃描器讀取一個CSV文件。該CSV有2列(名稱,描述),並說明字段中有長段(與和。)

我想知道什麼分隔符這個案例。

+1

描述是否可以包含換行符? – aioobe 2010-09-30 06:59:09

+0

可以在描述中有逗號嗎? – 2010-09-30 07:24:03

+1

thegravytalker:是的,操作狀態「描述字段有很長的段落(with,and。)」 – aioobe 2010-09-30 07:26:29

回答

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

如果你只得到了兩列,用逗號分隔,一個簡單的替代Scanner是隻用String.substring

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

或String.split – Thilo 2010-09-30 07:24:05

2

只需使用一個庫,用於讀取/寫入CSV像OpenCSV並且您不必重新發明輪子:)

+0

這也將處理字段和多行字符串等中的引號引號和逗號。 – Thilo 2010-09-30 07:23:44