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

如何读取文本文件数据创建带指定属性的Java Player对象

实现方案

第一步:定义Player实体类

普通Java版本(兼容Java 8及以上):

public class Player {
    // 对应四个业务属性
    private String name;
    private int maximum_health;
    private int current_health;
    private int no_of_wins;

    // 全参构造方法
    public Player(String name, int maximum_health, int current_health, int no_of_wins) {
        this.name = name;
        this.maximum_health = maximum_health;
        this.current_health = current_health;
        this.no_of_wins = no_of_wins;
    }

    // Getter方法,如需修改属性可自行补充Setter
    public String getName() { return name; }
    public int getMaximum_health() { return maximum_health; }
    public int getCurrent_health() { return current_health; }
    public int getNo_of_wins() { return no_of_wins; }
}

Java 16及以上版本可直接用record简化定义,无需手动写构造和Getter:

public record Player(String name, int maximum_health, int current_health, int no_of_wins) {}

第二步:读取文本文件生成Player对象

采用try-with-resources语法自动关闭流,避免资源泄露:

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

public class PlayerLoader {
    public static void main(String[] args) {
        // 替换为你的文本文件实际存储路径
        String filePath = "player_data.txt";
        Player player = null;

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            // 按顺序读取四行内容,和属性一一对应
            String name = br.readLine();
            int maxHealth = Integer.parseInt(br.readLine());
            int currentHealth = Integer.parseInt(br.readLine());
            int winCount = Integer.parseInt(br.readLine());

            // 构造目标对象
            player = new Player(name, maxHealth, currentHealth, winCount);

            // 验证结果可选
            System.out.println("player.name = " + player.getName());
            System.out.println("player.maximum_health = " + player.getMaximum_health());
            System.out.println("player.current_health = " + player.getCurrent_health());
            System.out.println("player.no_of_wins = " + player.getNo_of_wins());
        } catch (IOException e) {
            System.out.println("文件读取失败:" + e.getMessage());
        } catch (NumberFormatException e) {
            System.out.println("数字属性解析失败:" + e.getMessage());
        }
    }
}

注意事项

  • 执行代码前请将player_data.txt替换为你自己的文本文件实际路径
  • 如果文本内容行数、格式和要求不匹配会抛出对应异常,可根据业务需求调整异常处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:06:07