Java读取CSV文件到数组报错:Integer无法转换为int[]
我有一份CSV格式的数据文件,文件内容示例如下图:
我尝试将该CSV文件内容读取到ArrayList中,希望通过索引遍历ArrayList并打印其中存储的多类型值(包含String、double、int等类型),编写的实现代码如下:
public static void main(String[] args) throws IOException { System.out.println("Data from CSV file to be analysed:"+"\n"); String file = "jrc-covid-19-all-days-of-world_ASSIGNMENT-FIXED.csv"; ArrayList<Integer> lines = new ArrayList<Integer>(); String line = null; try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { int i = 0; while(((line = bufferedReader.readLine()) != null) && i<27) { String[] values = line.split(","); i++; System.out.println(Arrays.toString(values)); } } catch (IOException e) { e.printStackTrace(); } int thirdCountry[] = lines.get(3); int cp3 = thirdCountry[6]; System.out.println(cp3); //should return the value 107122 }
代码运行时抛出如下错误提示:incompatible types: Integer cannot be converted to int[].(类型不兼容:Integer无法转换为int数组)
错误产生原因
- 泛型声明不匹配:定义的
ArrayList<Integer>强制要求集合内存储的元素必须是Integer类型对象,但实际需求是存储每行CSV拆分得到的字符串数组,两者类型完全不符。调用lines.get(3)时编译器判定返回值是Integer类型,自然无法直接赋值给int[]数组变量,直接触发你看到的类型不兼容报错。 - 读取结果未存入集合:循环逻辑里只对每行内容做了拆分、打印操作,从未将拆分得到的
values数组添加到lines集合中,哪怕泛型声明正确,集合始终为空,后续调用get()方法会直接抛出索引越界异常。 - 缺少类型转换步骤:CSV文件读取的所有内容默认都是字符串类型,就算正确将数组存入集合,取出的数组元素也是
String类型,无法直接赋值给int类型变量。
代码修正方案
- 修改ArrayList泛型声明,指定存储元素类型为
String[],对应每行拆分后的字符串数组。 - 循环内完成行内容拆分后,调用
lines.add(values)将拆分结果存入集合。 - 从数组中取目标位置的值时,调用
Integer.parseInt()将字符串转为整数类型。 - 确认索引对应关系:集合、数组的索引均从0开始计数,要取第4行(索引3)第7列(索引6)的内容,需确认索引位置和预期行、列对齐,避免取错值。
修正后的可运行代码如下:
public static void main(String[] args) throws IOException { System.out.println("Data from CSV file to be analysed:"+"\n"); String file = "jrc-covid-19-all-days-of-world_ASSIGNMENT-FIXED.csv"; // 修正泛型类型,存储每行拆分后的字符串数组 ArrayList<String[]> lines = new ArrayList<>(); String line = null; try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { int i = 0; while(((line = bufferedReader.readLine()) != null) && i<27) { String[] values = line.split(","); // 将拆分后的行数据存入集合 lines.add(values); i++; System.out.println(Arrays.toString(values)); } } catch (IOException e) { e.printStackTrace(); } // 取出对应行的字符串数组 String[] thirdCountry = lines.get(3); // 将字符串转为int类型 int cp3 = Integer.parseInt(thirdCountry[6]); System.out.println(cp3); // 正常输出预期值107122 }
补充提示:如果CSV内容存在带逗号的引号包裹字段(比如地址、带千分位的数字),直接用
split(",")拆分会出现字段错位问题,这类场景建议直接使用成熟的CSV解析库(如OpenCSV、Apache Commons CSV)处理,避免手写拆分逻辑出错。
内容的提问来源于stack exchange,提问作者Francois200212
相关产品推荐
相关产品推荐

