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

如何读取文本文件每行开头整数并忽略其余内容?

解决方案:提取每行开头的整数并存入数组

针对你需要读取每行开头整数、忽略其余内容并将结果存入数组的需求,以下是两种可行的实现方案:

方法一:改进Scanner的使用

你之前的Scanner代码用next()按空白分割内容,导致注释部分被拆分输出。改为按行读取后处理每行内容,就能精准提取开头的整数:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class ReadIntegerFromFile {
    public static void main(String[] args) {
        ArrayList<Integer> integerList = new ArrayList<>();
        try {
            File programFile = new File("file.txt");
            Scanner scanner = new Scanner(programFile);
            
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                // 去除行首尾空白,避免空行或行首空格干扰
                String trimmedLine = line.trim();
                if (trimmedLine.isEmpty()) {
                    continue; // 跳过空行
                }
                // 按空白分割成两部分,只取第一部分(开头的整数)
                String[] lineParts = trimmedLine.split("\\s+", 2);
                try {
                    int num = Integer.parseInt(lineParts[0]);
                    integerList.add(num);
                    System.out.println(num); // 验证输出
                } catch (NumberFormatException e) {
                    // 遇到非整数开头的行时跳过,也可根据需求添加提示
                    System.out.println("跳过无效行:" + line);
                }
            }
            scanner.close();
            
            // 将集合转换为int数组(如果需要)
            int[] integerArray = integerList.stream().mapToInt(Integer::intValue).toArray();
            // 若需要Integer数组:
            // Integer[] integerArray = integerList.toArray(new Integer[0]);
            
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
            e.printStackTrace();
        }
    }
}

方法二:使用BufferedReader实现(纠正你的误解)

你之前的BufferedReader代码存在语法错误(reader.()应为reader.readLine()),而且未对行内容做处理。实际上BufferedReader完全可以实现需求,且大文件场景下效率更高:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class ReadIntegerWithBufferedReader {
    public static void main(String[] args) {
        ArrayList<Integer> integerList = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
            String line;
            
            while ((line = reader.readLine()) != null) {
                String trimmedLine = line.trim();
                if (trimmedLine.isEmpty()) {
                    continue;
                }
                // 找到第一个空白字符的位置,截取开头的整数部分
                int firstSpaceIndex = trimmedLine.indexOf(' ');
                String numStr;
                if (firstSpaceIndex == -1) {
                    numStr = trimmedLine; // 整行都是整数
                } else {
                    numStr = trimmedLine.substring(0, firstSpaceIndex);
                }
                try {
                    int num = Integer.parseInt(numStr);
                    integerList.add(num);
                    System.out.println(num);
                } catch (NumberFormatException e) {
                    System.out.println("跳过无效行:" + line);
                }
            }
            reader.close();
            
            // 转换为int数组
            int[] integerArray = integerList.stream().mapToInt(Integer::intValue).toArray();
            
        } catch (IOException e) {
            System.out.println("文件读取失败");
            e.printStackTrace();
        }
    }
}

两种方案都会将提取到的整数先存入ArrayList,最后可按需转换为数组。运行后都会输出你预期的结果:

2
3
40

内容的提问来源于stack exchange,提问作者HermitIX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:05:26