yakovliam
Member
I've tried to use the default Nukkit configuration API in the past, and I find it to be a pain and it requires a lot of effort to manage. To solve this I originally wrote my own for myself, but I thought I'd share it with all of you. For all of the classes I show you, you will have to adapt to your needs.
Here's main ConfigManager.class
(PASTEBIN https://pastebin.com/iURrvMrP)
If you see down at the bottom where I call `yamlParse`, that is the class `YAMLParse`, which is here.
(PASTEBIN https://pastebin.com/24MY0pRS)
Here's what I used to get data. Below is for string. You can use the method by calling `GetString("string-here")` E.G `GetString("messages.error")`
Message me here or on discord (yako#5080) if you have any questions, you'd like to see a feature, or I did something wrong. Thanks!
(I didn't share the full resource because it's not hard to figure out the rest for yourselves)
Here's main ConfigManager.class
Code:
public void Setup() throws IOException {
/*
YAML initialize
*/
mainDir = main.getDataFolder();
// load as file
configFile = new File(mainDir, "config.yml");
messagesFile = new File(mainDir, "messages.yml");
// directories
if(!mainDir.exists()){
mainDir.mkdirs();
}
// files exist
if(!configFile.exists()){
configFile.createNewFile();
try{
DefaultConfig();
}catch (Exception e){
e.printStackTrace();
}
}
if(!messagesFile.exists()){
configFile.createNewFile();
try {
DefaultMessages();
}catch (Exception e){
e.printStackTrace();
}
}
// load configs
YAMLParse yamlParse = new YAMLParse(main);
// INIT settings
settings.SetMap(yamlParse.ParseConfig(configFile.getName().replace(".yml", "") + ".yml"));
// INIT lang
lang.SetMap(yamlParse.ParseConfig(messagesFile.getName().replace(".yml", "") + ".yml"));
}
If you see down at the bottom where I call `yamlParse`, that is the class `YAMLParse`, which is here.
Code:
Map<String, Object> ParseConfig(String resourceName){
Yaml yaml = new Yaml();
InputStream iS = null;
try {
iS = new FileInputStream(main.getDataFolder() + File.separator + resourceName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return (Map<String, Object>) yaml.load(iS);
}
Here's what I used to get data. Below is for string. You can use the method by calling `GetString("string-here")` E.G `GetString("messages.error")`
Code:
public String GetString(String key){
String[] parts = key.split("\\.");
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) configCfg;
for(int x = 0; x < parts.length; x++){
if(x != (parts.length - 1)) {
map = (LinkedHashMap<String, Object>) map.get(parts[x]);
}else{
try {
return (String) map.get(parts[x]);
}catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
(I didn't share the full resource because it's not hard to figure out the rest for yourselves)