Saving, loading, and reloading the config file

Now that we have the config.yml file and it is located in the default package of the plugin, we need to be able to save it to a user's server. Once the file is saved, the user will be able to edit it as they please. Saving the config file is as simple as adding the following method call to the onEnable method, as follows:

saveDefaultConfig();

This will copy config.yml to plugins/MobEnhancer/config.yml. If the file already exists, then this line of code will do nothing.

The loading of the config file is done automatically by Spigot, and there is no need for you to do anything in addition to this in your plugin besides using getConfig when you actually want to access the configuration file.

Reloading config.yml is fairly simple to include; we will add it in the form of a command, as follows:

@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
    reloadConfig();
    sender.sendMessage("MobEnhancer config has been reloaded");
    return true; //The command was executed successfully
}

We will put this method inside the main class for now. Ensure that the class also implements CommandExecutor. Do not forget to register the command with the following line:

getCommand("mobenhancerreload").setExecutor(this);

The command should also be added to plugin.yml, as always. It is a good idea to add a permission node at this point too. The new plugin.yml file looks like this:

name: MobEnhancer
main: com.codisimus.mobenhancer.MobEnhancer
version: 0.2
description: Modifies Mobs as they spawn
commands:
  mobenhancerreload:
    description: Reloads the config.yml file of the plugin
    aliases: [mereload, merl]
    usage: /<command>
    permission: mobenhancer.rl
    permission-message: You do not have permission to do that
permissions:
  mobenhancer.rl:
    default: op

Now, your plugin will have a reload command. This means that when you edit config.yml, you can reload the plugin rather than restarting the entire server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172