2011-08-08 54 views
0

我一直在嘗試使用列表來存儲來自.csv文件的數據,但由於我是新來的使用列表,我似乎無法得到它上班。我搜索了很多教程,但他們都沒有爲我工作。我肯定錯過了什麼。這是我到目前爲止有:使用列表來存儲來自BufferedReader文件的數據

 int row = 0; 
     int col = 0; 

     String fileInput = JOptionPane.showInputDialog(null, 
       "Please enter the path of the CSV file to read:"); 

     File file = new File(fileInput); 

     BufferedReader bufRdr; 
     bufRdr = new BufferedReader(new FileReader(file)); 
     String line = null; 

     ArrayList<String[]> arrayOfNumbers = new ArrayList<String[]>(); 

     //read each line of text file 
     while((line = bufRdr.readLine()) != null) { 
      StringTokenizer st = new StringTokenizer(line,","); 
      col=0; 

      while (st.hasMoreTokens()) { 
       //get next token and store it in the array 
       // UNSURE WHAT TO PUT HERE 
      } 
      row++; 
     } 

然後我想在列表中的數據存儲到一個多維數組稱爲String[][] numbers。我應該做什麼的想法?

回答

1

在您初始化字符串的multidim數組之前,您需要知道它的維數,它與您的最大列大小相似(萬一這些行不具有相同數量的「令牌」)以及行數是你得到的行數。

int row = 0; 
    int col = 0; 

    String fileInput = JOptionPane.showInputDialog(null, 
      "Please enter the path of the CSV file to read:"); 

    File file = new File(fileInput); 

    BufferedReader bufRdr; 
    bufRdr = new BufferedReader(new FileReader(file)); 
    String line = null; 

    ArrayList<StringTokenizer> arrayOfNumbers = new ArrayList<StringTokenizer>(); 

    //read each line of text file 
    while((line = bufRdr.readLine()) != null) { 
     StringTokenizer st = new StringTokenizer(line,","); 
     arrayOfNumbers.add(st); 

     int actColCount = st.countTokens(); 

     if (col < actColCount) { 
      col = actColCount; 
     } 
    } 

    row = arrayOfNumbers.size(); 

現在您可以遍歷存儲的行並將它們放入您的數組中。也許會出現一些ArrayOutOfBound異常,但沒有詳細說明。但應該這樣做。

String[][] numbers = new String[row][col]; 

    for (int i=0; i<row; i++) { 

     StringTokenizer st = arrayOfNumbers.get(i); 

     int j = 0; 
     while(st.hasMoreElements()) { 
      numbers[i][j] = st.nextElement(); 
      j++; 
     } 
    } 

請小心陣列中的這些領域,因爲沒有在該行,以填補該行每一列/場,足以元件,其不具有價值。這個字段返回一個null。

相關問題