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

Java如何读取二维文本文件并确定目标数组的大小?

确定二维文本文件的数组大小并拆分数据到多个作业数组

咱们先明确核心需求:要先搞清楚有多少个学生(即表头之外的数据行数)和有多少个作业列(表头的字段数量),这样就能精准确定各个作业数组的长度了。下面给你两种可行的实现思路:

思路1:两次遍历文件,先统计大小再初始化数组

这种方式适合你想提前固定数组长度的场景,先读一遍文件统计行数和列数,再读第二遍填充数据:

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

public class GradeProcessor {
    public static void main(String[] args) {
        File gradeFile = new File("inputHW7.txt");
        int studentCount = 0;
        int homeworkCount = 0;

        // 第一次遍历:统计学生数量和作业列数
        try (Scanner countScanner = new Scanner(gradeFile)) {
            // 读取表头,确定作业的数量
            if (countScanner.hasNextLine()) {
                String[] headers = countScanner.nextLine().split("\\s+");
                homeworkCount = headers.length;
            }
            // 统计学生行数(剩下的每一行对应一个学生)
            while (countScanner.hasNextLine()) {
                countScanner.nextLine();
                studentCount++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        // 根据统计结果初始化数组
        String[] studentNames = new String[studentCount];
        int[] HW1arr = new int[studentCount];
        int[] HW2arr = new int[studentCount];
        int[] HW3arr = new int[studentCount];
        int[] HW4arr = new int[studentCount];
        int[] HW5arr = new int[studentCount];

        // 第二次遍历:读取数据填充数组
        try (Scanner dataScanner = new Scanner(gradeFile)) {
            // 跳过表头行
            dataScanner.nextLine();
            int index = 0;
            while (dataScanner.hasNextLine()) {
                String line = dataScanner.nextLine().trim();
                // 用\\s+分割,兼容多个空格/制表符的情况
                String[] parts = line.split("\\s+");
                studentNames[index] = parts[0];
                HW1arr[index] = Integer.parseInt(parts[1]);
                HW2arr[index] = Integer.parseInt(parts[2]);
                HW3arr[index] = Integer.parseInt(parts[3]);
                HW4arr[index] = Integer.parseInt(parts[4]);
                HW5arr[index] = Integer.parseInt(parts[5]);
                index++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 测试输出示例
        System.out.println(studentNames[0] + "的HW1成绩:" + HW1arr[0]);
    }
}

思路2:用动态集合存储,最后转数组(更灵活)

如果不想两次遍历文件,推荐用ArrayList动态存储数据,最后再转换成数组,不用提前统计大小,代码更简洁:

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

public class GradeProcessor {
    public static void main(String[] args) {
        File gradeFile = new File("inputHW7.txt");
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<Integer> hw1List = new ArrayList<>();
        ArrayList<Integer> hw2List = new ArrayList<>();
        ArrayList<Integer> hw3List = new ArrayList<>();
        ArrayList<Integer> hw4List = new ArrayList<>();
        ArrayList<Integer> hw5List = new ArrayList<>();

        try (Scanner scanner = new Scanner(gradeFile)) {
            // 跳过表头行
            scanner.nextLine();
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                // 跳过空行(如果文件里有的话)
                if (line.isEmpty()) continue;
                String[] parts = line.split("\\s+");
                nameList.add(parts[0]);
                hw1List.add(Integer.parseInt(parts[1]));
                hw2List.add(Integer.parseInt(parts[2]));
                hw3List.add(Integer.parseInt(parts[3]));
                hw4List.add(Integer.parseInt(parts[4]));
                hw5List.add(Integer.parseInt(parts[5]));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        // 将集合转为数组
        String[] studentNames = nameList.toArray(new String[0]);
        int[] HW1arr = hw1List.stream().mapToInt(Integer::intValue).toArray();
        int[] HW2arr = hw2List.stream().mapToInt(Integer::intValue).toArray();
        int[] HW3arr = hw3List.stream().mapToInt(Integer::intValue).toArray();
        int[] HW4arr = hw4List.stream().mapToInt(Integer::intValue).toArray();
        int[] HW5arr = hw5List.stream().mapToInt(Integer::intValue).toArray();

        // 测试输出示例
        System.out.println(studentNames[1] + "的HW5成绩:" + HW5arr[1]);
    }
}

小提示

  • 用split("\\s+")分割文本,能兼容多个空格、制表符的情况,避免因为格式不规范导致数组越界。
  • 记得处理FileNotFoundException,确保文件路径正确。
  • 如果文件中存在空行,要加判断跳过,避免读取无效数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:33:23