How to avoid triggering an ArrayIndexOutOfBoundsException while parsing empty positions in a line of CSV?

血红的双手。 提交于 2019-12-07 14:16:26

First of all, String.split() is not a great CSV parser: it doesn't know about quotes and will mess up as soon as one of your quoted values contains a comma.

That being said, by default String.split() leaves out empty trailing elements. You can influence that by using the two-argument variant:

String[] values = line.split(",", -1);
  • -1 (or any negative value) means that the array will be as large as necessary.
  • Using a positive value gives a maximum amount of splits to be done (meaning that everything beyond that will be a single value, even if it contains a comma).
  • 0 (the default if you use the one-argument value) means that the array will be as large as necessary, but empty trailing values will be left out of the array (exactly as it happens to you).

As a general rule you should never, ever hack up your own (faulty) parser if a working one already exists. CSV is not easy to parse correctly, and String.split will not do the job since CSV allows , to be used between "'s without working as separaters.

Consider using OpenCSV. This will solve both the problem you have now and the problem you will face when a user uses a , as part of the data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!