我正在创建一个实用程序类,它将使人们更容易解析 csv 字符串并返回字符串数组的数组。
我的代码几乎可以工作,但由于某种原因,当我在第一行中获取结果时,我期望看到 1 行并看到第一行上串联的几行。
简单示例:
a,b,c,d
e,f,g,h
预期:{a,b,c,d}, {e,f,g,h}
结果:{a,b,c,d,e,f,g}
public class csvParse
{
protected String originalCSV;
protected int skipToLine;
protected ArrayList<ArrayList<String>> parsedList;
public ArrayList<ArrayList<String>> getParsedList()
{
return parsedList;
}
public void setParsedList(ArrayList<ArrayList<String>> parsedList)
{
this.parsedList = parsedList;
}
public csvParse(String incomingCSV, int skipToLine)
{
super();
this.originalCSV = incomingCSV;
this.skipToLine = skipToLine;
this.parsedList = new ArrayList<ArrayList<String>>();
execute();
}
protected void execute()
{
// breaking this so there's an error. read below
//TODO: Make sure you have data out to X. May use a try/catch?
String row;
String lines[] = this.originalCSV.split("\\n?\\r");
ArrayList<String> temp = new ArrayList<String>();
try{
for (int i = this.skipToLine; i < lines.length; i++)
{
row = lines[i];
//split on commas
String[] RowData = row.split(",");
for (int x = 0; x < RowData.length; x++)
{
temp.add(RowData[x]);
}
this.parsedList.add(temp);
}
}
finally{
}
}
}
最佳答案
在您的 execute()
方法中,您不会重置 temp
变量,因此它会从所有行获取数据。只需将初始化移至外部 for
循环内即可。
关于java - csv 到字符串数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6374435/