Skip to content

Making use of the API

JesFot edited this page Mar 10, 2020 · 1 revision

Reading a file

Starting with an example:

IYAMLConfiguration myConfig = Configurations.newYAMLConfig(new File("."), "fileName");

This line will open the file located at ./fileName.yaml, the first argument being the folder in which the file is located and the second, the name of the file without extension.

You can also read the YAML this way:

IYAMLConfiguration myConfig = Configurations.newConfig(ConfigurationTypeCls.YAML_CONFIG, new File("."), "fileName", null);

ConfigurationTypeCls is typed and therefore you won't need to cast the result.

If you don't mind casting (or you don't know the type you are using) :

IFlatConfiguration myFlatCfg = Configurations.newConfig(ConfigurationType.YAML, new File("."), "fileName", null);
IYAMLConfiguration myConfig = (IYAMLConfiguration) myFlatCfg;

Reloading from file

You have the possibility to reload the file from which you read the configuration first time :

try {
    myConfig.reload();
} catch (FileFormatException ffe) {
    ...
}

Note the try...catch block, because the file may have changed independently, a FileFormatException is thrown if there is something unexpected while reading the file, all important informations (like requested format, file path) are provided as part of the exception message.

Saving the file

There is nothing simpler than saving any values you may have changed :

myConfig.save();

And done ! Everything is safe now.

Note: save() and reload() can be called from any of the sections for a single file, it will save/reload everything not just the section.

Getting some values

From there, you can get any values from your configuration, there is three ways to achieve that :

String someThing = myConfig.getString("key"); // Will return null if no key is found (or not a string)
// Or
String someThing = myConfig.getString("key", "defaultValue"); // Will return "defaultValue" if key is not found
// Or
try {
    String someThing = myConfig.tryGetString("key"); // Throws a NoFieldException if "key" does not exists or is not a string
} catch (NoFieldException e) {
    ...
}

Those methods exists as part of a flat configuration.

Configuration Sections

With non-flat configuration you can get sub sections :

IYAMLConfiguration child1 = myConfig.getSubSection("mySuperPath");

If the requested section does not exists, it will be created, linked and returned.

You can also get the parent of a section (or the root section of the file) :

child1.getParent() == child1.getSubSection("..") == myConfig;

child1.getRoot() == child1.getSubSection("."); // Bukkit-type root symbol is '.'

Setting some values

You can also set your values :

myConfig.setString("key", "anotherValue");
myConfig.setSubSection("mySuperPath", child1);

It works exactly the same as with the getters.