【问题标题】:Read a csv-file value by value with Scanner, useDelimiter(";") not working使用 Scanner 按值读取 csv 文件值,useDelimiter(";") 不起作用
【发布时间】:2014-10-24 08:59:58
【问题描述】:

我正在尝试使用 Scanner.useDelimiter(";") 按值读取 CSV 文件值。
但是Scanner.nextLine() 仍然返回整行而不是单个值。

CSV 文件如下所示:

0.00034;0.1;0.3;0.6;1,00E-13

我的代码:

Scanner iStream = new Scanner(new InputStreamReader(new FileInputStream(file.cvs);
iStream.useDelimiter(";");
String[] test = new String[5];
for (int i = 0; i < 5; i++) {
    test[i] = iStream.nextLine();
}

结果:

"0.00034;0.1;0.3;0.6;1,00E-13"  

预期结果:

"0.00034", "0.1", "0.3", "0.6", "1,00E-13"  

这可能吗,还是我应该使用String.split()? 我错过了什么吗?

【问题讨论】:

  • 我真的建议opencsv,太棒了!

标签: java csv java.util.scanner delimiter


【解决方案1】:

除了这个问题对于OpenCSV这样的解析库来说是现成的,nextLine不考虑分隔符模式。请改用next

test[i] = iStream.next();

【讨论】:

  • 我知道,这很简单。我会研究一下 opencsv,谢谢!
【解决方案2】:

来自 Java Scanner 文档:

public String next()

Finds and returns the next complete token from this scanner. 
A complete token is preceded and followed by input that matches the delimiter pattern.

这确实回答了您的问题。但是,我不确定next 在开始和结束时的行为,因为它必须由分隔符“前后”。也许有人可以填写这个?

您可以在分隔符中添加额外的字符,例如 \netc。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-25
    • 2021-01-04
    • 2014-11-17
    • 2019-03-09
    • 2017-01-18
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多