2017-02-24 42 views
0

我读一个CSV文件看起来像以下:阅读CSV文件,标题和多个列

Red Blue Green 
1st Y N  
2nd Y Y  N 
3rd N   Y 

我所要的输出是这样的

1红Ÿ
1蓝ñ
第二红色Ÿ
第二蓝色Y
第二届绿色ň
3红ñ
3rd Green Y

我将颜色行拉入数组中,但我不知道如何获得所需的输出。下面是我到目前为止的代码:

public String readFile(File aFile) throws IOException { 
    StringBuilder contents = new StringBuilder(); 
    ArrayList<String> topRow = new ArrayList<String>(); 

    try { 
     BufferedReader input = new BufferedReader(new FileReader(aFile)); 

     try { 
      String line = null; 

     while ((line = input.readLine()) != null){ 
      if(line.startsWith(",")) { 
       for (String retval: line.split(",")) { 
       topRow.add(retval); 
       //System.out.println(retval); 

       } 
      } 
     } 
     } 
     finally { 
     input.close(); 
     } 
    } 
    catch (IOException ex){ 
     ex.printStackTrace(); 
    } 

    return contents.toString(); 
} 
+0

不要重新发明轮子。使用现有的***调试过的*** CSV库(有几个)。 –

回答

1

第一行需要读取和阵列/列表(我喜欢这里阵列,因为它会更快)存储。然后,需要解析和存储后续行,并从第一行获取列名,现在将其存储为数组。

在代码中,我直接用换行符写了一个字符串,我建议使用一个字符串数组列表(长度为3),以便将来可以轻松使用它。

public String readFile(File aFile) throws IOException { 

String data = ""; 

try { 
    BufferedReader input = new BufferedReader(new FileReader(aFile)); 
    String line = null; 
    int cnt = 0; 
    String[] topRow = new String[0]; 
    while ((line = input.readLine()) != null){ 
     if(cnt==0){ 
      String[] l = line.split(","); 
      topRow = new String[l.length-1]; 
      for(int i= 0; i<l.length-1; i++){ 
       topRow[i] = l[i+1]; 
      } 
     } 
     else{ 
      String[] l = line.split(","); 
      for(int i= 1; i<Math.min(l.length, topRow.length+1); i++){ 
       if(!l[i].equals("")){ 
        String row = ""; 
        row = l[0]; 
        row = row + " " + topRow[i-1]; 
        row = row + " " + l[i]; 
        if(data.equals(""))data = row; 
        else data = data + "\n" + row; 
       } 
       } 
     } 
     cnt++; 
    } 
} 
catch (IOException ex){ 
    ex.printStackTrace(); 
} 
return data; 

}