Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bukkit ConfigurationSection getKeys

I have a bukkit config file that looks like this:

effected mobs:
  skeleton:
    lower hp limit: 0
    upper hp limit: 0
  zombie:
    lower hp limit: 0
    upper hp limit: 0
  spider:
    lower hp limit: 0
    upper hp limit: 0

I'm trying to get a set that contains [skeleton, zombie, spider] and any others that may be added by giving it the key "effected mobs". I have looked at this similar question and tried the following code:

public class Main extends JavaPlugin implements Listener{
    public FileConfiguration config;
    public Set<String> mobsEffected;

    public void onEnable(){
        config = getConfig();
        mobsEffected = config.getConfigurationSection("effected mobs").getKeys(false);
        Bukkit.getLogger().info(String.valueOf(mobsEffected.size() ));

    }
}

but the size is logged as 0, when it should be 3. Any advice?

like image 643
donsavage Avatar asked Nov 23 '25 10:11

donsavage


1 Answers

So you actually want to get a Set of Strings based on your Configuration Entry. This should work:

public class Main extends JavaPlugin implements Listener {
    public FileConfiguration config;
    public Set<String> mobsEffected;

    public void onEnable() {
        // you have to initialize your set!
        mobsEffected = new HashSet<String>();
        // this creates the Config
        File Cfgpath = new File("plugins/yourpluginnamehere");
        File Cfg =  new File("plugins/yourpluginnamehere/config.yml");
        try {
            Cfg.createNewFile();
        } catch (IOException e) {
            Cfgpath.mkdirs();
            try {
                Cfg.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        config = YamlConfiguration.loadConfiguration(Cfg);
        // Now it loops through all the Keys in the Configuration Section
        // "effected mobs" and adds every key to your set!
        for (String key : config.getConfigurationSection("effected mobs").getKeys(false)) {
            mobsEffected.add(key);
        }
        Bukkit.getLogger().info(String.valueOf(mobsEffected.size()));

    }
}

Please Make Sure that you replace yourpluginnamehere with the Name of your Plugin. You have to take the same String at both of the times where you have to replace it(Case Sensitive!).

Then it will automatically Create a Config Directory with a blank config.yml for you at first run.

At first run you will also get a NullPointerexception because the ConfigurationSection doesn't exist yet. So just go to your plugin's Folder and insert your config content to the newly created config.yml.

like image 96
Miromed Avatar answered Nov 24 '25 23:11

Miromed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!