2016-05-16 140 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()]);