我正在解析 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/