2011-06-16 85 views
0

我创建一个实用工具类,这将使人们更容易解析一个CSV字符串并返回一个字符串数组的数组的数组的数组。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{ 

    } 
} 
} 
+2

又有什么问题? – pickypg 2011-06-16 15:31:50

+0

incomingCSV如何生成? – Atreys 2011-06-16 15:33:49

+0

尝试魔'按Ctrl-Shift键F' – 2011-06-16 16:49:02

回答

2

在你​​方法,你不要重置temp变量,所以它从获取数据所有行。只需在外部for -loop内移动您的初始化即可。

+0

呃。我怎么没看出来。谢谢。 – kireol 2011-06-16 15:44:19

1

创建“TEMP”,通过该行变为外循环。因此,您不断地将字段添加到同一个临时对象。你想在循环中移动这个创建,所以你为每一行创建一个新的对象。

另外请注意,你是不是处理一个领域内嵌入的逗号。也许这不会在你的数据中发生。但CSV标准是一个字段可能用引号引起来,在这种情况下,引号应该被删除。如果它包含在引号中,则可以包含逗号。如果一个字段包含引号,它们应该加倍。例如:

a,"b,c","He said, ""Hello""" 

包含三个字段:

a 
b,c 
He said, "Hello" 
+0

我有处理引号中的逗号的代码,我只是没有包括它按照SO的要求来保持简单。感谢虽然:) – kireol 2011-06-16 15:46:16