2014-04-19 69 views
0

我想知道是否有任何方法可以讀取除第一行(標題)和每行第一列之外的CSV文件?我想如果我跳過數組nextLine [0]的第0個元素,我可以跳過每一行的第一列,但任何人都可以幫助我如何跳過包含標題的第一行,我只需要檢索數據,而不是標題。下面是我的代碼:通過CSVReader讀取除CSV第一行之外的CSV

if (CSValreadyExists) 
    { 
     try { 
      reader = new CSVReader(new FileReader(csvfile)); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     String [] nextLine; 
     try { 
      while ((nextLine = reader.readNext()) != null) { 
       // nextLine[] is an array of values from the line 
       //System.out.println(nextLine[0] + nextLine[1] + "etc..."); 

       scalesFromCSV.add(nextLine[0]); // Factor 
       scalesFromCSV.add(nextLine[1]); // Scale 
       scalesFromCSV.add(nextLine[2]); // Scale 
       scalesFromCSV.add(nextLine[4]); // Scale 
       scalesFromCSV.add(nextLine[5]); // Scale 
       scalesFromCSV.add(nextLine[6]); // Scale 

       Toast.makeText(this, nextLine[1] + "-" + nextLine[2] 
         + "-" + nextLine[3] + "-" + nextLine[4] + "-" + nextLine[5] 
           + "-" + nextLine[6], Toast.LENGTH_LONG).show(); 
      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

回答

0

例如:

if (CSValreadyExists) 
    { 
     try { 
      reader = new CSVReader(new FileReader(csvfile)); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     String [] nextLine; 
     try { 
      boolean headersConsumed = false; // helper flag 
      while ((nextLine = reader.readNext()) != null) { 
       // nextLine[] is an array of values from the line 
       //System.out.println(nextLine[0] + nextLine[1] + "etc..."); 

       if(!headersConsumed){ // if headers not consumed 
        headersConsumed = true; 
        continue; // skip line with headers 
       } 

       scalesFromCSV.add(nextLine[0]); // Factor 
       scalesFromCSV.add(nextLine[1]); // Scale 
       scalesFromCSV.add(nextLine[2]); // Scale 
       scalesFromCSV.add(nextLine[4]); // Scale 
       scalesFromCSV.add(nextLine[5]); // Scale 
       scalesFromCSV.add(nextLine[6]); // Scale 

       Toast.makeText(this, nextLine[1] + "-" + nextLine[2] 
         + "-" + nextLine[3] + "-" + nextLine[4] + "-" + nextLine[5] 
           + "-" + nextLine[6], Toast.LENGTH_LONG).show(); 
      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
+0

完美,謝謝,它工作:) – user2387107

0

你並不需要編寫跳過頭的自定義邏輯,你可以使用相應的構造函數。最後一個參數是skipLines,默認值爲零(CSVReader.DEFAULT_SKIP_LINES),所以它讀取標題。

new CSVReader(new FileReader(pathToData), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, 1);