了解 CSV 文件的分隔符
这可能是一个简单的问题,但我一直未能找到满意的答案。我正在用 Java 编写一个类,它需要接收一个 .csv 文件,该文件在三列中填充了双精度数。显然,.csv 文件使用逗号作为分隔符,但是当我尝试使用扫描仪设置它们时,扫描仪什么也没发现。有什么建议吗?
Scanner s = null;
try {
s = new Scanner(source);
//s.useDelimiter("[\\s,\r\n]+"); //This one works if I am using a .txt file
//s.useDelimiter(", \n"); // This is what I thought would work for a .csv file
...
} catch (FileNotFoundException e) {
System.err.format("FileNotFoundException: %s%s", e);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
输入示例为:
12.3 11.2 27.0
0.5 97.1 18.3
等。
感谢您的宝贵时间!
编辑:已修复!找到正确的分隔符并意识到我使用的是 hasNextInt() 而不是 hasNextDouble()。 /捂脸
This may be a simple question but I have not been able to find a satisfactory answer. I am writing a class in Java that needs to take in a .csv file filled with doubles in three columns. Obviously a .csv file uses commas as the delimiters, but when I try setting them with my scanner, the scanner finds nothing. Any advice?
Scanner s = null;
try {
s = new Scanner(source);
//s.useDelimiter("[\\s,\r\n]+"); //This one works if I am using a .txt file
//s.useDelimiter(", \n"); // This is what I thought would work for a .csv file
...
} catch (FileNotFoundException e) {
System.err.format("FileNotFoundException: %s%s", e);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
A sample input would be:
12.3 11.2 27.0
0.5 97.1 18.3
etc.
Thank you for your time!
EDIT: fixed! Found the correct delimiters and realized I was using hasNextInt() instead of hasNextDouble(). /facepalm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请考虑以下事项:
应该只有五个 - 最后一个逗号位于引号块中,不应将其拆分。
不要重新发明轮子。有一些开源库可以处理这种行为。
快速谷歌搜索得到了http://opencsv.sourceforge.net/,我确信还有其他。
Consider the following:
Should only be five - the last comma is in a quote block, which should not get split.
Don't reinvent the wheel. There are open source libraries to handle this behavior.
A quick google search yielded http://opencsv.sourceforge.net/ and I'm sure there's others.
如果您尝试读取每个单独的项目,请尝试:
然后
s.next()
将从 CSV 返回一个项目。If you are trying to read each individual item, try:
Then
s.next()
would return an item from the CSV.为什么 CSV 分隔符中有 \n?如果 CSV 和 TXT 文件具有相同的内容,Java 之间没有区别。
我想你会想要
或者
Why have you got a \n in your CSV delimiter? Java doesn't have a difference between CSV and TXT files, if they have the same content.
I would think you would want
or
有多种解决方法:
方法 1:
在文件扩展名中使用条件语句( if-else / switch )。
方法2:
正如其他答案所建议的,使用这个:
There are several methods to workaround:
Method 1:
use conditional statements ( if-else / switch ) in file extension.
Method 2:
as other answers suggested, use this: