使用标题和多列读取Java中的CSV文件

时间:2017-02-24 16:59:54

标签: java arrays csv matrix

我正在阅读如下所示的CSV文件:

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

我希望输出类似于

第一红Y .. 第一蓝N 第二红Y 第二蓝Y 第二次绿色N
第3红N 第3次绿色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(); 
}

1 个答案:

答案 0 :(得分: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; 

}