Search code examples
javapluginsminecraftbukkit

Bukkit - How to read from a YML file and use in an if statements


I would like to read data from my config.yml. It's saving data like (playerName: value). I want to check, if player's name value is equals to 0, then ban him. But still don't know how to read those values. I was searching around spigot forum but nothing worked.

@EventHandler
    public void OnDeath(PlayerDeathEvent event) {
        Player player = event.getEntity().getPlayer();
        String playerName = player.getName();

        int lives;

        if (!livesMap.containsKey(player)) {
            // Set the default amount of lives to 2. (3 minus 1, since the player already died once)
            lives = 2;

            plugin.getConfig().set(playerName, lives);
            plugin.saveConfig();
        } else {
            // Subtract one from the player's lives
            lives = livesMap.get(player) - 1;

            // Saving playerName and lives
            plugin.getConfig().set(playerName, lives);
            plugin.saveConfig();
        }

        livesMap.put(player, lives);

My data is saving like this, but i want to know what method should i use to read values.


Solution

  • Lucky for you, bukkit already has classes you can use for this!

    import org.bukkit.configuration.file.FileConfiguration;
    
    FileConfiguration config = getConfig();
    

    This call will inherently load your config.yml file.

    You can then access values by doing something like this:

    config.getString("yml.object.here");
    

    Let me know if you have any other questions!

    TIP: If you store your player names in a list you can get a list of them!