[Tutorial] Create A Configuration File with YAML!

Discussion in 'Resources' started by Jayjay110, May 4, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    Jayjay110

    Ok I made a new Tut :)
    OLD (open)

    Step 1: First things first, we must set up our variables so go ahead and tweak these to ur liking:

    Code:
    static String mainDirectory = "plugins/pluginname";
    File file = new File(mainDirectory + File.separator + "config.yml");
    

    Step 2: Second we must create a new load method so we can load our files with ease. Add this code to your main plugin class file that your code resides in for easy access

    Code:
    public Configuration load(){
    
            try {
                Configuration config = new Configuration(file);
                config.load();
                return config;
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    Step 3: Now we want to make it so that when out plugin runs, we can check if the config file has been made yet and if not, create it
    Code:
    new File(mainDirectory).mkdir();
    
    
            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                //load stuff on statup here
            }
    
    Step 4: Now we are done, all we need to do is read and write to the file, to do so u can make two new methods for even easier access
    Code:
        public void write(String root, Object x){ //just so you know, you may want to write a boolean, integer or double to the file as well, therefore u wouldnt write it to the file as "String" you would change it to something else
        	Configuration config = load();
            config.setProperty(root, x);
            config.save();
        }
    
        public  String read(String root){
        	Configuration config = load();
            return config.getString(root);
        }
    
    Step 5: Now from anywhere you can call plugin.read("foo.bar"); and you will get the value stored by it and you can also call plugin.write("foo.bar","is poo");

    Try it :)

    Well I hope this helps some people, I'd like to give thanks to sammy and adam coz they helped me start out with this stuff :)


    First things first, create a new class called, Config :)
    Add this:
    Config.java (open)

    PHP:
    package com.servegame.n1p.MyPlugin;

    import java.io.File;
    import java.util.List;

    import org.bukkit.util.config.Configuration;

    public class 
    Config {
        private static 
    MyPlugin plugin;
        public 
    Config(MyPlugin instance) {
            
    plugin instance;
        }

           public 
    String directory "plugins" File.separator +plugin.getDescription().getName();
           
    File file = new File(directory File.separator "config.yml");


        public 
    void configCheck(){
            new 
    File(directory).mkdir();


            if(!
    file.exists()){
                try {
                    
    file.createNewFile();
                    
    addDefaults();

                } catch (
    Exception ex) {
                    
    ex.printStackTrace();
                }
            } else {

                
    loadkeys();
            }
        }
        private 
    void write(String rootObject x){
            
    Configuration config load();
            
    config.setProperty(rootx);
            
    config.save();
        }
        private 
    Boolean readBoolean(String root){
            
    Configuration config load();
            return 
    config.getBoolean(roottrue);
        }

        private 
    Double readDouble(String root){
            
    Configuration config load();
            return 
    config.getDouble(root0);
        }
        private List<
    StringreadStringList(String root){
            
    Configuration config load();
            return 
    config.getKeys(root);
        }
        private 
    String readString(String root){
            
    Configuration config load();
            return 
    config.getString(root);
        }
        private 
    Configuration load(){

            try {
                
    Configuration config = new Configuration(file);
                
    config.load();
                return 
    config;

            } catch (
    Exception e) {
                
    e.printStackTrace();
            }
            return 
    null;
        }
        private 
    void addDefaults(){
            
    plugin.log.info("Generating Config File...");
        
    write(plugin.enabledstartuptrue);
         
    loadkeys();
        }
        private 
    void loadkeys(){
            
    plugin.log.info("Loading Config File...");
            
    plugin.enabled readBoolean(plugin.enabledstartup);

            }
    }


    Now for the sake of the tutorial, we will make the plugin check if its enabled on startup, in your main class add 2 variables, 1 is the path in a config file for the enabled startup to be displayed as and the other is the enabled to check if the plugin is enabled :), Then we need to add a config object to allow access to the config class

    Like so:
    PHP:
    public String enabledstartup "Enabled On Startup";
    public 
    boolean enabled;
    Config config = new Config(this);
    Now its that simple, all you have to do now is add the check for the config into your onEnable, like so:

    PHP:
    config.configCheck();
    Now run your code! see what happens! If you make something happen when enabled is true different things will happen. ... thats not explained right but whateva :p

    Now all you need to do to make a config file that reads variables and stuff, is add a line in the config class, where load defaults and add defualts is, to do this just use common sense its not that hard.

    Im sorry for my bad english, even tho I speak english as my first language, Im just a bit...Iffy, today I had my exam for english and im like wow I suck lol... anyway :3

    Umm Idk :)
     
  2. Offline

    goz3rr

    Really helped, thanks!
     
  3. Offline

    RazorFlint

    Sweet Thanks !
     
  4. Offline

    vildaberper

    There is plugin.getDataFolder(), which will return mainDirectory. :)
     
  5. Offline

    Jayjay110

    :p Lol, I just put it like that so that people could understand it better :) good pickup tho :D
     
  6. Offline

    niccholaspage

    Change
    Code:
    public void write(String root, String x){
    to
    Code:
    public void write(String root, Object x){
    This way, a boolean and everything can be written to the YML.
     
    4am likes this.
  7. Offline

    imjake9

    You don't need to do all that file initialization, you can just call this.getConfiguration(). Much simpler, you just have to call it from the plugin's main class.
     
  8. Offline

    Jayjay110

    Thanks bro :)

    how do you get the data then?
     
  9. Offline

    imjake9

    Huh? I don't see what you mean. You just do this:
    Code:
    Configuration config = this.getConfiguration();
    String myProperty = config.getString("my-property", "Hello World!");
    //etc.
    You use it just like any other configuration object...
     
  10. Offline

    Jayjay110

    Oh riight... wow my brain doesnt work at full blast at 12:00 at night :3
     
  11. Offline

    tips48

    so just for verification, in the example would the write method change the config to
    root = x
    could someone show me quickly the code if you wanted to write, say something in the config that says
    example = true
    thanks a ton, this has helped alot <3
     
  12. Offline

    4am

    Nope, the example writes whatever value you assign to "root" as a YAML node and whatever you assign to x as it's value.

    For example, if you did write("example","true"); your YAML file would be:
    but if you did write("this.is.fun","yes!"); you'd end up with

    Bukkit does not have built in support for simple key/value configs, and honestly once you've done it more than once, YAML is simple enough. The best part is that when you read it back in to bukkit, you just ask like this: String myResult = theConfig.read("this.is.fun"); and it returns "yes!" as a string.
     
    Jayjay110 likes this.
  13. Offline

    ttwj

    ty, this really helped :D
     
  14. Offline

    Pandarr

    There's currently no way to inject comments into the yml file using Configuration correct? Aside from doing a filereader/writer? I looked at the API but nothing stuck out at me.
     
  15. Offline

    4am

    I think you can write a node with no value (a null) with a key name of "#The Comment" but I haven't tried this yet. I've seen evidince of a plugin doing this, but it seemed to have failed and written '#The comment": to the file; not sure if this was a bug on the plugin's end or if the system isn't geared for it.

    The best way to generate a default config file is to keep a copy in your JAR and just write it out to your plugin's DataFolder() if a config doesn't exist; that way you can be certain of exactly how a config will look when first installed, including extra line breaks and comment lines; I think if you write out a config then it might remove extra line breaks but I again have not tested this.
     
  16. Offline

    Jayjay110

    I dont like doing it this way because u have less control over the file. to write it, just add a method that writes it on startup, and make it do something like:
    write(defaultpath,"Zomgihashax");
    its that simple :)]
    Then you can read it with:
    defualt = readS(defaultpath);
     
  17. Offline

    Minecraft93

    Hey Jayjay could you reorganize the tutorial? or is it all corrected? Id like to figure this out lol :p.
     
  18. Offline

    Jayjay110

    Yeah Ill reorganise it soz lol :p
     
  19. Offline

    Minecraft93

    thanks, but now how do we create variables to setup the configurable options?
    Cuase on my plugin EvilBed im trying to create configurable messages/ damage ammount/ chat color.
     
  20. Offline

    Pandarr

    I have a method I call if the config file doesn't exist. It sets up the defaults. If the file does exist then it just reads from the file. So once the configuration file is generated the user is free to update it. If they want a fresh config file they can then just delete the file and it'll regenerate automatically.
     
  21. Offline

    Jayjay110

    I believe I have this in my config class also...

    To create messages in your config file, create a config path and a variable for the message, the config path can be somethign like message.damadgeamountC, and that would give:
    message:
    damadgeamountC:
    in the config, then create the message as a string like damadgeamount = damadgeamountC...

    I got exams now, if you dont get how it works, look through my source of the mystery box plugin or something...
     
  22. Offline

    MG127

    how do i read config files of unknown length?
    such as:
    Code:
    parts:
        '1':
               a: blub
               b: test
        '2':
               a: blah
               b: world
         '3':
    ...
    
    or if its easier
    Code:
    parts:
        -    a: blub
             b: test
        -    a: blah
             b: world
    
     
  23. Offline

    Pandarr

    Don't know the code off the top of my head but I believe you get the parts node and there should be a method to get the child nodes. Or there's a method to config that you supply the parent node... not sure.
     
  24. Offline

    Jayjay110

    No you run a for loop like so, its really simple:
    List<String> lst = readStringList("parts");
    if (lst[0] != null){
    for (Iterator<String> items = lst.iterator(); lst.hasNext();){
    String i = items.next();
    //add strings to a list here, this will loop throu the parts heading and read all values in the subheading :)
    }
    }
     
  25. Offline

    MG127

    lst.hasNext() is not avaible for List<String>, maybe lst.iterator().hasNext() ?
    lst[0]!=null isnt working either, should be replaced with !lst.isempty()

    i only need to know how to create arrays of classes, but i'll take that to another topic
     
  26. Offline

    THEK

    ok. I hate posting in these topics because I'm sure I look stupid. Is this example ready to copy into a plugin (obviously changing MyPlugin to the name of the main class)? I copied it over but eclipse is complaining about ".log" saying "Cannot be resolved or is not a field".
     
  27. Offline

    Kalman Olah

    I'd like to know how I write proper comments to a YML file...Currently I'm just using write("#comment here","");, but it shows up as
    Code:
    #comment here: ''
     
  28. Offline

    MG127

    or how to write the file that is stored in the jar ... :)
     
  29. Offline

    Jayjay110

    .log is the minecraft logger, you need to create it first if you havnt, most people do it to show there plugin is enabled, you can do so by adding this line to ur main class:
    Logger log = Logger.getLogger("Minecraft");

    I have no clue :3 sorry lol

    I dont know how to do that either but...

    e
    yes it is list.iterator().hasNext(); my mistake, google how to use a for loop for a list in java but that code shuld work, and yeah u could replace it with lst.isEmpty(), I just didnt notice that whenn i was doing it lol :p
     
  30. Offline

    MG127

    it was item.hasNext() :D we were both wrong
    Code:
    if (!lst.isEmpty()){
     for (Iterator<String> items = lst.iterator(); item.hasNext();){
     String i = items.next();
    
    more questions :)
    how do i write and read a list?
    root:
    - element1
    - element2
    and check if they are empty

    how do i write empty roots, so i can check them later with readString("root").isEmpty();
    how do i check if a root exists or not? if a root doesn't exists, a readString will result in a nullpointerexception
     
Thread Status:
Not open for further replies.

Share This Page