You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取文件字符索引报IndexOutOfBoundsException异常如何解决

报错原因与解决方案

根本原因

Java 中字符串、列表的索引均从0开始计数,长度为N的对象合法索引范围是0 ~ N-1。你遇到的报错说明你尝试访问长度为120的对象的索引120,超出了合法范围。

代码存在的问题与修复方案

  • 问题1:location.txt行索引读取错误
    Files.readAllLines()返回的行列表是从0开始索引的,你的lineNumb初始值设为1,循环到最后会出现读取行索引等于location.txt总行数的情况,直接触发越界。
    修复:将int lineNumb = 1修改为int lineNumb = 0。
  • 问题2:SFile.txt读取的字符串未做长度校验
    你从location.txt读取到索引值nn后,直接调用s.charAt(nn),没有判断nn是否小于s的长度,当存储的索引值大于等于SFile内容长度时就会触发你遇到的报错。
    修复:拿到nn后增加校验逻辑:
int nn = Integer.parseInt(line);
s = bufrd.readLine();
if (nn >= s.length()) {
    System.out.printf("索引%d超出SFile内容长度%d,跳过读取%n", nn, s.length());
    lineNumb++;
    continue;
}
  • 问题3:IO操作逻辑冗余
    你在循环中重复读取location.txt、重复打开SFile.txt,既降低效率也容易引发IO异常。建议优化为:先一次性读取所有location索引存入List,再一次性读取SFile的全部内容,之后再遍历索引取值。

优化后的参考代码

try {
    // 一次性读取所有位置索引
    List<String> locationLines = Files.readAllLines(Paths.get("location.txt"));
    // 一次性读取SFile的内容
    String sFileContent = Files.readString(Paths.get("SFile.txt"));
    int sLength = sFileContent.length();
    // 遍历索引取值
    for (String line : locationLines) {
        int nn = Integer.parseInt(line.trim());
        if (nn >= sLength) {
            System.out.printf("索引%d超出SFile内容长度%d,跳过%n", nn, sLength);
            continue;
        }
        System.out.println("The Location " + nn  + " is : "+ sFileContent.charAt(nn));
    }
} catch (IOException e) {
    e.printStackTrace();
}

内容的提问来源于stack exchange,提问作者Asst. Farah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:09:03