繁体   English   中英

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

[英]Reading CSV file in Java with headers and multiple columns

我正在读取一个如下所示的CSV文件:

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

我希望输出像

第一红Y
1st蓝色N
第二红Y
第二蓝Y
第二绿N
第三红N
第三绿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(); 
}

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

在代码中,我直接编写了带换行符的字符串,我建议使用字符串数组列表(长度为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; 

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM