Java执行File I/O读取州人口文件时出现IndexOutOfBoundsException异常
异常原因
你遇到的IndexOutOfBoundsException是由于存储州名的ArrayList<String> states和存储人口的ArrayList<Integer> pops长度不一致导致的。报错堆栈指向sortStates方法,说明你在该方法中按相同索引同时取两个列表的对应元素,当索引超过较短列表的长度时就会抛出越界异常。
而两个列表长度不一致的根源是你的文件读取逻辑存在缺陷:
- 分隔符设置时机错误:仅在读取州名的else分支才将分隔符设为逗号,后续循环不会自动重置为默认分隔符,导致后续读取逻辑混乱
- 同组数据拆分判断:你把同一行的州名和人口拆分到if、else两个分支判断,无法保证每行刚好存入一个州名+一个人口,很容易出现某一列表漏存、多存元素的问题
- 换行处理逻辑有漏洞:读完人口后的
nextLine()调用可能吞掉有效内容或者残留换行符,干扰后续读取
修复方案
推荐按行读取的方案,逻辑清晰容错性强,修改后的readFile方法如下:
public static void readFile(ArrayList<String> states, ArrayList<Integer> pops){ try{ Scanner read = new Scanner(new File("StatesPop.txt")); while(read.hasNextLine()){ String line = read.nextLine().trim(); // 跳过空行避免异常 if(line.isEmpty()) continue; // 按逗号拆分当前行 String[] lineParts = line.split(","); states.add(lineParts[0].trim()); pops.add(Integer.parseInt(lineParts[1].trim())); } read.close(); }catch(FileNotFoundException fnf){ System.out.println("File was not found."); } }
如果要沿用原有的分隔符思路实现,需要在初始化Scanner时就统一设置分隔符,不要中途修改:
public static void readFile(ArrayList<String> states, ArrayList<Integer> pops){ try{ Scanner read = new Scanner(new File("StatesPop.txt")); // 统一设置分隔符为逗号或换行符 read.useDelimiter(",|\\n"); while(read.hasNext()){ String state = read.next().trim(); int pop = read.nextInt(); states.add(state); pops.add(pop); // 跳过残留的换行空白 if(read.hasNextLine()) read.nextLine(); } read.close(); }catch(FileNotFoundException fnf){ System.out.println("File was not found."); } }
内容的提问来源于stack exchange,提问作者Nimtheria
相关产品推荐
相关产品推荐

