2013-08-22 60 views
0

我有一個csv編碼一些項目的詞庫,預計每行的條目數對於不同的行是不同的。openCSV CSVReader需要具有相同數量字段的行嗎?

第一行包含25個標記/同義詞。其餘的線條較少。但是所有讀取的String[]的長度均爲25.較短的行填充了空字符串。

有什麼辦法可以避免這種情況發生?

我的代碼如下所示:

search examination exploration hunt inquiry inspection investigation pursuit quest research chase frisking going-over inquest pursual pursuance pursuing rummage scrutiny shakedown fishing expedition legwork perquisition wild-goose chase witch hunt 
school schule 
saint st. st 

當我打印的String []項目一個接一個,我得到這個:

從CSV

CSVReader reader = new CSVReader(new FileReader("thesaurus.csv", '\t')); 
String [] nextLine; 
while ((nextLine = reader.readNext()) != null) { 
    System.out.println("length of the row: "+ nextLine.length); 
} 

採樣線

'school', 'schule', , , , , , , , , , , , , , , , , , , , , , , , 
'saint', 'st.', 'st', , , , , , , , , , , , , , , , , , , , , , , 
+0

@Reimeus新增。我不是指明確的填充。我的意思是,在'reader.readNext()'中初​​始化String []的方式可能是問題。或者我錯過了一些非常明顯的東西......謝謝。 – Navneet

+0

@Reimeus我的csv中沒有尾隨標籤。我後處理爲'removeAll()'空的或空的條目。 – Navneet

回答

0

我想你的輸入CSV文件中有空格。

String[] nextLine; 
    while ((nextLine = reader.readNext()) != null) { 
     for (String line : nextLine) { 
      System.out.println(line.replaceAll(" ", ".")); 
     } 
    } 

如果沒有尾隨空格,這是輸出。

search..examination..exploration....hunt....inquiry.inspection..investigation...pursuit.quest...research....chase...frisking....going-over..inquest.pursual.pursuance...pursuing....rummage.scrutiny....shakedown...fishing.expedition..legwork.perquisition....wild-goose.chase....witch.hunt 
school..schule 
saint...st..st 

這是輸出,如果有尾隨空格。

search..examination..exploration....hunt....inquiry.inspection..investigation...pursuit.quest...research....chase...frisking....going-over..inquest.pursual.pursuance...pursuing....rummage.scrutiny....shakedown...fishing.expedition..legwork.perquisition....wild-goose.chase....witch.hunt 
school..schule............................ 
saint...st..st............................................. 
相關問題