簡體   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