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

如何将文本文件按行读取存入固定大小String数组并解决相关报错

错误原因

java.util.NoSuchElementException 抛出的核心原因是调用读取方法时,Scanner已经没有可读取的内容了,除此之外代码还有几处逻辑错误:

  • 实例化Scanner时直接传入文件路径字符串,不会读取对应路径的文件,只会把路径字符串本身作为解析内容
  • 强制循环读取30000次,只要文件实际内容行数少于30000,后续调用scanner.next()时就会抛出该异常
  • 使用next()方法读取不符合按行读取的需求:next()遇到空格、制表符、换行符都会中断读取,要严格按行读应该用nextLine()
  • 直接System.out.println(arrayin)打印数组只会输出数组的内存地址,无法查看内部存储的内容

修复后的代码

首先导入依赖类:

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

功能实现代码:

public static String[] arrayin = new String[30000];

public static void CreateDict(String filepath) throws IOException {
    // try-with-resources语法会自动关闭Scanner,避免资源泄漏
    try (Scanner scanner = new Scanner(new File(filepath))) {
        int index = 0;
        // 仅当还有可读取的行、且数组未填满时才执行读取
        while (scanner.hasNextLine() && index < arrayin.length) {
            arrayin[index] = scanner.nextLine();
            index++;
        }
        // 打印数组全部内容
        System.out.println(Arrays.toString(arrayin));
    }
}

如果需求要求数组30000个位置必须全部填充非null值,可以在读取完文件内容后,对剩余的位置补默认值,比如补空字符串:

while (index < arrayin.length) {
    arrayin[index] = "";
    index++;
}

内容的提问来源于stack exchange,提问作者The Grey Wolf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:24:01