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

Java实现从txt文件读取数据封装为Question对象存入ArrayList

没问题,我来帮你实现这个需求!咱们分两步走:先定义符合要求的Question实体类,再编写读取文件、创建对象并存入ArrayList的逻辑。

解决方案

1. 定义Question实体类

首先得把Question类写好,对应你提到的所有属性,我给它加了全参构造方法,方便直接从文件读取的属性批量创建对象,也可以按需添加getter/setter方法:

public class Question {
    private String question;
    private String option1;
    private String option2;
    private String option3;
    private String answer;
    private double difficulty;
    private int category;

    // 全参构造方法,用于直接从文件属性创建对象
    public Question(String question, String option1, String option2, String option3, String answer, double difficulty, int category) {
        this.question = question;
        this.option1 = option1;
        this.option2 = option2;
        this.option3 = option3;
        this.answer = answer;
        this.difficulty = difficulty;
        this.category = category;
    }

    // 可选:添加getter/setter方法,方便后续操作对象属性
    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    // 其他属性的getter/setter可以按需补充
}

2. 读取文件并构建Question集合

下面提供两种实现方式,你可以根据自己的Java版本和习惯选择:

方式一:传统BufferedReader读取(兼容所有Java版本)

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

public class QuestionBankLoader {
    public static void main(String[] args) {
        ArrayList<Question> questionBank = new ArrayList<>();
        String filePath = "questions.txt"; // 注意文件路径,确保程序能访问到

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 逐行读取文件内容
            while ((line = br.readLine()) != null) {
                // 按逗号分割属性,这里假设文件格式规范,属性本身不含逗号
                String[] attributes = line.split(",");
                
                // 先校验属性数量,避免数组越界
                if (attributes.length != 7) {
                    System.err.println("格式错误,跳过该行:" + line);
                    continue;
                }

                try {
                    // 转换数据类型:difficulty是double,category是int
                    double difficulty = Double.parseDouble(attributes[5]);
                    int category = Integer.parseInt(attributes[6]);

                    // 创建Question对象并加入题库
                    Question question = new Question(
                            attributes[0],
                            attributes[1],
                            attributes[2],
                            attributes[3],
                            attributes[4],
                            difficulty,
                            category
                    );
                    questionBank.add(question);
                } catch (NumberFormatException e) {
                    System.err.println("数据类型转换失败,跳过该行:" + line);
                    e.printStackTrace();
                }
            }

            System.out.println("成功加载" + questionBank.size() + "道题目到题库");
        } catch (IOException e) {
            System.err.println("读取文件时发生异常:");
            e.printStackTrace();
        }
    }
}

方式二:Java 8+ Stream API实现(更简洁)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class QuestionBankStreamLoader {
    public static void main(String[] args) {
        String filePath = "questions.txt";
        List<Question> questionBank;

        try {
            questionBank = Files.lines(Paths.get(filePath))
                    .map(line -> {
                        String[] attributes = line.split(",");
                        if (attributes.length != 7) {
                            System.err.println("格式错误,跳过该行:" + line);
                            return null;
                        }
                        try {
                            double difficulty = Double.parseDouble(attributes[5]);
                            int category = Integer.parseInt(attributes[6]);
                            return new Question(
                                    attributes[0], attributes[1], attributes[2],
                                    attributes[3], attributes[4], difficulty, category
                            );
                        } catch (NumberFormatException e) {
                            System.err.println("数据类型转换失败,跳过该行:" + line);
                            return null;
                        }
                    })
                    .filter(question -> question != null) // 过滤掉转换失败的空对象
                    .collect(Collectors.toList());

            System.out.println("成功加载" + questionBank.size() + "道题目到题库");
        } catch (IOException e) {
            System.err.println("读取文件时发生异常:");
            e.printStackTrace();
        }
    }
}

额外提醒

  • 文件路径:如果questions.txt和代码不在同一目录,记得使用绝对路径(比如"C:\\test\\questions.txt"或"/home/user/questions.txt")。
  • 特殊格式处理:如果题目/选项本身包含逗号,直接用split(",")会出错,这种情况建议用专业的CSV解析库(比如OpenCSV)来处理。
  • 异常处理:代码里加了基础的异常捕获,避免某一行格式错误导致整个程序崩溃,你可以根据需求调整异常处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:39:30