Java CSV文件解析不解析末尾的空列

标签 java csv

我正在解析 CSV 文件,但是有一行的最后 9 列为空,并且用逗号分隔的字符串会忽略剩余的空列。

下面是演示这一点的代码:

String s="L2,,,,,,,,,,,,,,,,,,108.50,-188.04,,,,,,,,,";
String[] columns = s.split(",");
System.out.println(columns.length);

列的大小是 20,而它应该是 29。有什么想法吗?

最佳答案

查看 String.split 的文档:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

因此您需要查看 other split method 的选项

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

强调我的。

您需要:

String[] columns = s.split(",", -1);

关于Java CSV文件解析不解析末尾的空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440357/

相关文章:

java - 云存储 - 上传图像时文件的内容类型显示为数据

java - 像 jquery 通知一样的 Swing 通知

python - 对 csv 文件的第一列进行硬编码,然后使用 Python 导入 google 分析

python - 从 CSV 文件中删除新行

python-3.x - 如何从 CSV 输出中删除换行符

带有 boolean 值的 java.lang.NullPointerException

java - 如何从 Access 附件字段中提取图像并将其放入 JLabel 中

java - 用于搜索的同义词数据结构

python - 列表的数组 Python

python - 如果行不相等,如何通过公共(public)列合并两个 csv 文件?