openCSV CSVReader是否需要具有相同字段数的行?

时间:2013-08-22 22:00:57

标签: java csv opencsv

我有一个csv编码某些项目的词库,并且,预计每行的条目数对于不同的行是不同的。

第一行包含25个令牌/同义词。其余的线路较小。但是所有读取的String[]都有25个。较短的行用空字符串填充。

有没有办法避免这种情况发生?

我的代码如下所示:

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);
}

来自csv的示例行:

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 []项目时,我得到了这个:

'school', 'schule', , , , , , , , , , , , , , , , , , , , , , , , 
'saint', 'st.', 'st', , , , , , , , , , , , , , , , , , , , , , , 

1 个答案:

答案 0 :(得分: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.............................................