java csv分割,关于Java分割命令解析Csv文件

I have a csv file in the below format.

H,"TestItems_20100107.csv",07/01/2010,20:00:00,"TT1198","MOBb","AMD",NEW,,

I require the split command to ignore the commas inside the double quotes . So i used the below split command from an earlier post. Pasted the URL that i took this command

String items[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

System.out.println("items.length"+items.length);

When i run for this CSV data I am getting the items.length printed as 8. The last two commas at the end of line after "NEW" are ignored. I want the split command to pick up these commas and return me the length as 10. It's not picking up the null commas if it's in end but it's picking it up if it's in the middle of string. Not sure what i need to modify in the split command to resolve this issue. Also in the csv file Double quotes within the contents of a Text field can be repeated (e.g. "This account is a ""large"" one")

解决方案

There's nothing wrong with the regular expression. The problem is that split discards empty matches at the end:

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.

A workaround is to supply an argument greater than the number of columns you expect in your CSV file:

String[] tokens = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)", 99);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值