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

如何从文本文件读取数据并构建Animal对象存入数组?

问题描述

现有一段Java代码用于读取指定路径的animals.txt文本文件:

public void getAnimalsFromTextFile() throws IOException {
    String file = "C:\\Users\\nikit\\OneDrive\\Desktop\\animals.txt";
    BufferedReader inFile = new BufferedReader(new FileReader(file));
    String line;
    int cnt = 0;
    while ((line = inFile.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line,"");
        if(st.hasMoreTokens()) {
            String line1 = st.nextToken();
            StringTokenizer st1 = new StringTokenizer(line1, " ");
            while (st1.hasMoreTokens()) {
                String att = st1.nextToken();
                strings.add(att);
            }
        }
    }
}

文本文件animals.txt内容为:

Jackie Jack Boston
Marty Bird California
Donald Duck Netherlands

希望从该文件中构建3个Animal对象,格式如下:

Animal animal =  new Animal(Jackie, Jack, Boston);

最终将这些Animal对象存入数组中,但现有代码仅将所有属性存入strings集合,请求指导如何修改代码实现需求。

修改方案

1. 替换存储容器

把原来用来存属性的strings集合,换成专门存储Animal对象的List(数组长度固定,用List先临时存储更灵活):

// 在类中定义成员变量
private List<Animal> animalList = new ArrayList<>();

2. 简化解析逻辑并构建对象

原代码的双层StringTokenizer完全没必要,直接按空格分割每行内容,每行刚好对应Animal的三个属性,分割后直接构造对象:

public void getAnimalsFromTextFile() throws IOException {
    String file = "C:\\Users\\nikit\\OneDrive\\Desktop\\animals.txt";
    BufferedReader inFile = new BufferedReader(new FileReader(file));
    String line;
    
    while ((line = inFile.readLine()) != null) {
        // 跳过空白行,避免分割后数组长度不足报错
        if (line.trim().isEmpty()) {
            continue;
        }
        // 按任意数量空格分割每行内容
        String[] attrs = line.split("\\s+");
        // 构造Animal对象并加入List
        Animal animal = new Animal(attrs[0], attrs[1], attrs[2]);
        animalList.add(animal);
    }
    // 手动关闭流,避免资源泄漏
    inFile.close();
}

3. 转换为Animal数组

如果最终需要数组而非List,可在方法末尾或单独逻辑中完成转换:

Animal[] animalArray = animalList.toArray(new Animal[0]);

4. 优化:使用try-with-resources自动关流

原代码未保证流的关闭,建议用try-with-resources语法让JVM自动管理流的关闭,避免资源泄漏:

public void getAnimalsFromTextFile() throws IOException {
    String file = "C:\\Users\\nikit\\OneDrive\\Desktop\\animals.txt";
    // try块结束后自动关闭BufferedReader
    try (BufferedReader inFile = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = inFile.readLine()) != null) {
            if (line.trim().isEmpty()) {
                continue;
            }
            String[] attrs = line.split("\\s+");
            Animal animal = new Animal(attrs[0], attrs[1], attrs[2]);
            animalList.add(animal);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:28:11