[英]Dealing with commas when reading a CSV file
There is nothing wrong in the other part.另一部分没有错。 I read the lines of the excel files.
我阅读了excel文件的行。 But I want to split the cells of this excel.
但我想拆分这个excel的单元格。 I use the statement
String []values1 = data1.split(",");
我使用语句
String []values1 = data1.split(",");
and values1[5]=values1[5].replace('"', ' ').trim();
. But there is a particular cell which there is a ,
in it. This comma disrupts the arranged order. How should I deal with it?和
values1[5]=values1[5].replace('"', ' ').trim();
。但是有一个特定的单元格,其中有一个,
。这个逗号破坏了排列顺序。我应该怎么做处理它?
File DopCan = new File(filesnames[0]);
try
{
Scanner scanner = new Scanner(DopCan);
scanner.nextLine();
scanner.nextLine();
while(scanner.hasNext())
{
String data = scanner.nextLine();
String []values = data.split(",");
values[5]=values[5].replace('"', ' ').trim();
if(Integer.parseInt(values[5])==0)
{
i++;
}
else
{
break;
}
}
scanner.close();
Scanner scanner1 = new Scanner(DopCan);
scanner1.nextLine();
scanner1.nextLine();
while(scanner.hasNext())
{
ArrayList <PollingPlace> files = new ArrayList();
while (scanner1.hasNext())
{
int n=0;
String data1 = scanner1.nextLine();
String []values1 = data1.split(","); //Problem here
scanner1.nextLine();
String data3=scanner1.nextLine();
String []values3 = data3.split(",");
values1[5]=values1[5].replace('"', ' ').trim();
values1[7]=values1[7].replace('"', ' ').trim();
values1[14]=values1[14].replace('"', ' ').trim();
values3[14]=values3[14].replace('"', ' ').trim();
files.add(new PollingPlace(Integer.parseInt(values1[5]),Integer.parseInt(values1[7]),Integer.parseInt(values1[14]),Integer.parseInt(values3[14])));
scanner1.nextLine();
scanner1.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
There's an easy answer and a correct one.有一个简单的答案和一个正确的答案。
Easy answer is to parse the string more robust with regexp, say,简单的答案是使用正则表达式更健壮地解析字符串,例如,
(?:\s*(?:\"([^\"]*)\"|([^,]+))\s*,?)+?
But CSV turns out to be a rather diffucult for that as there are a number of corner cases to consider.但是 CSV 被证明是相当困难的,因为有许多极端情况需要考虑。
Correct answer is to use a library for that, and as it happens there is manifold of them: JSefa , OpenCSV , etc.正确的答案是为此使用一个库,并且碰巧有很多: JSefa , OpenCSV等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.