2016-05-16 197 views
1

我有一個數組rawData[]其中包含來自csv文件的字符串。 現在我想要做的是將保存爲字符串的所有整數複製到新的int []中。從字符串[]提取數字

我試過下面的代碼,但我得到兩個錯誤。

  1. 錯誤「異常‘java.io.IOException的’永遠不會在相應try塊拋出」最後的try/catch

  2. 當我嘗試將dataList轉換爲數組我得到: 「Incompatible types. Found: 'java.lang.Object[]', required: 'int[]'」 我知道,不知何故ArrayList包含對象,但我怎樣才能得到它的工作?


 public static int[] getData(){ 
       String csvFile = "C:\\Users\\Joel\\Downloads\\csgodoubleanalyze.csv"; 
       BufferedReader br = null; 
       String line = ""; 
       String cvsSplitBy = ","; 
       String[] rawData = new String[0]; 
       List<Integer> dataList = new ArrayList<Integer>(); 

       try { 

        br = new BufferedReader(new FileReader(csvFile)); 
        while ((line = br.readLine()) != null) { 

         // use comma as separator 
         rawData = line.split(cvsSplitBy); 
        } 

       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
        if (br != null) { 
         try { 
          br.close(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 

       for (String s : rawData){ 
        try { 
         dataList.add(Integer.parseInt(s)); 
        } 
        catch (IOException e){ 
         e.printStackTrace(); 
        } 
       } 

       int[] data = dataList.toArray(); 

       return data; 

回答

2
  1. Integer.parseInt(s)不拋出IOException。它拋出一個NumberFormatException

  2. List.toArray不能產生原始類型的數組,所以你必須將它更改爲Integer[] data = dataList.toArray(new Integer[dataList.size()]);