Java CSV文件解析不会在末尾解析空列 [英] Java CSV file parsing does not parse empty columns at end

查看:330
本文介绍了Java CSV文件解析不会在末尾解析空列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am parsing a CSV file, however there is one row were the last 9 columns are empty and the string split by comma ignores the remains empty columns.

这里是用来证明这一点的代码:

Here is code to demonstrate this:

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

列的大小是20,应该是29.任何想法??

The size of columns is 20, when it should be 29. Any ideas??

推荐答案

查看 String.split


此方法的作用就像通过调用给定表达式和limit参数为零的双参数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.

因此,您需要查看其他 split 方法

So you need to look at the options for the other split method


limit参数控制模式的应用次数,因此影响结果数组的长度。如果限制n大于零,那么模式将最多应用n - 1次,数组的长度将不大于n,并且数组的最后一个条目将包含超出最后匹配分隔符的所有输入。 如果n是非正数,那么模式将被应用尽可能多次,并且数组可以具有任何长度。如果n为零,那么模式将被应用尽可能多次,数组可以具有任何长度,并且尾随空字符串将被丢弃。

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文件解析不会在末尾解析空列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆