2013-08-21 116 views
0

我有一個.csv文件,它具有逗號以及雙引號分隔值。如何使用帶有多個逗號和雙引號的掃描器在java中讀取.csv文件

現在我想解析逗號分隔值,當雙引號中有值時,我希望掃描儀使用雙引號作爲分隔符。

示例行解析:

123,學生 「考試的通知」, 「模式應該是一樣的,有效的,正確的」

現在

我想分析它喜歡:

123 //comma seperated 
student 
exam notification //when "" it should be double quote separated 
pattern should be same,validated,proper //ignore , comma in double quotes 

代碼,我曾嘗試:

scanner.useDelimiter(",|\""); 

因此,它可以同時使用,並且「」它確實很好,但在betwe它打印空白行,其中,「罷工,也不能忽略雙引號之間的逗號。

任何想法如何排序?

回答

0

使用CSV解析器像OpenCSV照顧之類的東西逗號引述元素,跨越多個值線等自動。您也可以使用該庫將您的文本序列化爲CSV。

CSVReader reader = new CSVReader(new FileReader("file.csv")); 

String [] nextLine; 
// prints the following for the line in your question 
while ((nextLine = reader.readNext()) != null) { 
    System.out.println(nextLine[0]); // 123 
    System.out.println(nextLine[1]); // student 
    System.out.println(nextLine[2]); // exam notification 
    System.out.println(nextLine[3]); // pattern should be same,validated,proper 
} 
0

有幾種方式來實現你想要做什麼,

1)使用現有的庫,它支持解析CSV的像拉維Thapliyal和Oibaf它建議。

2)你可以提供你的方法

  a). if every line in your CSV have a uniform format like : 
      line 1 : 123,student,"exam notif","word , word , word" 
      line 2 : 45345,not student,"no exam notif","word,word,word" 
    you can say like 

     while(scan.hasNextLine()){ 
     String line = scan.nextLine(); 
     //split it using double quotes first 
     temp = line.split("\""); 
     //then just remove commas outside the double quoted objects 
     for(int x = 0; x<temp.length; x++){ 
      if(temp[x].startsWith(",")) {temp[x] = temp[x].substring(1,temp[x].length()); } 
      if(temp[x].endsWith(",")) {temp[x] = temp[x].substring(0,temp[x].length()-1); } 
     } 

至於這個程序員而言,Java沒有任何現有的類,方法多的分隔符,但也有一些圖書館,可以使生活更輕鬆爲你 ,但你總是有一個選擇,提供自己的方法。 GUD運氣

相關問題