Java CSV file parsing does not parse empty columns at end

后端 未结 3 702
野趣味
野趣味 2020-12-17 00:20

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

3条回答
  •  孤城傲影
    2020-12-17 01:06

    The docs of split says:

    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.

    split(String regex) calls the overloaded split method with a limit of 0.That's why you have an array length of 20, all the empty strings after -188.04 are discarded in the resulting array.

    If you want to get all the empty trailing strings, you can give a negative limit to say that you want to apply the pattern as many times as possible.

    String[] columns = s.split(",", -1); //length is 29 there
    

    Although it's not hard to parse CSV, you may also want to look about using a CSV parser.

提交回复
热议问题