YAML file reading, writing, saving, and loading?

Discussion in 'Plugin Development' started by xboxnolifes, Jul 26, 2012.

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

    xboxnolifes

    Can somebody give a quick run-through on how to make editable YML files that can be edited through methods and not just though the file. I do NOT want config file methods.

    I need to be able to save all players to a list, and change a value set to their name (string or integer will work, not boolean).

    If anyone would take the time to help me it would be greatly appreciated as I could not get it working for a few hours now.
     
  2. Offline

    Gonzo0193

    Code:java
    1.  
    2. File playersConfigFile;
    3. FileConfiguration playersConfig;
    4.  
    5. playersConfigFile = new File(getDataFolder(), "players.yml");
    6. playersConfig = YamlConfiguration.loadConfiguration(playersConfigFile);
    7.  
    8. if(!event.getPlayer().hasPlayedBefore()) //If the player hasnt played before (read)
    9. {
    10. plugin.playersConfig.set("Players.Score." + event.getPlayer().getDisplayName(), 0); //Create their name in the config file and set their score to 0 (write)
    11. try {
    12. plugin.playersConfig.save(plugin.playersConfigFile); //Save the file
    13. } catch (IOException e) {
    14. // TODO Auto-generated catch block
    15. e.printStackTrace();
    16. }
    17. }
    18.  


    Thats what i have, however ill probably move where it saves to a different location :p.
     
  3. Offline

    xboxnolifes

    Okay, I did most of that, i'll try it again. (Tomorrow, it's almost 4:00pm here.)
     
  4. Offline

    pzxc

    I keep a global hashmap of all the different configs I use:

    HashMap<String,YamlConfiguration> configs = new HashMap<String,YamlConfiguration>();

    Then I have some helper methods that let me interface with them:

    Code:
    YamlConfiguration config(String configName) {
        if (!configs.containsKey(configName)) configs.put(configName, YamlConfiguration.loadConfiguration(new File(getDataFolder(), configName + ".yml")));
        return configs.get(configName);
    }
    ^--- with this I call config("myconfig1").set(field, value) or .getString or .getBoolean or any of the other config methods you can use on the default config

    Code:
    boolean saveConfig(String configName) {
    if (!configs.containsKey(configName)) configs.put(configName, YamlConfiguration.loadConfiguration(new File(getDataFolder(), configName + ".yml")));
    try { configs.get(configName).save(new File(getDataFolder(), configName + ".yml")); return true; }
    catch (IOException e) { log.severe("IO Error while saving file '" + configName + ".yml' to plugin data folder."); e.printStackTrace(); return false; }
    }
    ^--- with this I call saveConfig("myconfig1") to write the changes to disk
     
  5. Offline

    xboxnolifes

    I keep getting this error upon starting the server:

    Code:
    2012-07-27 15:33:50 [SEVERE] java.lang.NullPointerException
    2012-07-27 15:33:50 [SEVERE]at me.XboxNoLifes.QuantumRewards.QuantumRewards.loadYamls(QuantumRewards.java:59)
    2012-07-27 15:33:50 [SEVERE]at me.XboxNoLifes.QuantumRewards.QuantumRewards.onEnable(QuantumRewards.java:46)
    2012-07-27 15:33:50 [SEVERE]at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:215)
    2012-07-27 15:33:50 [SEVERE]at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337)
    2012-07-27 15:33:50 [SEVERE]at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:386)
    2012-07-27 15:33:50 [SEVERE]at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:264)
    2012-07-27 15:33:50 [SEVERE]at org.bukkit.craftbukkit.CraftServer.enablePlugins(CraftServer.java:246)
    2012-07-27 15:33:50 [SEVERE]at net.minecraft.server.MinecraftServer.t(MinecraftServer.java:387)
    2012-07-27 15:33:50 [SEVERE]at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:374)
    2012-07-27 15:33:50 [SEVERE]at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:208)
    2012-07-27 15:33:50 [SEVERE]at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:438)
    2012-07-27 15:33:50 [SEVERE]at net.minecraft.server.ThreadServerApplication.run(SourceFile:492)
    


    Here is my code:

    PHP:
    package me.XboxNoLifes.QuantumRewards;
     
    import java.io.File;
    import java.io.IOException;
    import java.util.logging.Logger;
     
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.PlayerInventory;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    import net.milkbowl.vault.economy.Economy;
     
    public class 
    QuantumRewards extends JavaPlugin {
     
        final 
    File file = new File(getDataFolder(), "completed.yml");
        final 
    FileConfiguration completed YamlConfiguration.loadConfiguration(file);
        public final 
    Logger logger Logger.getLogger("Minecraft");
        public static 
    QuantumRewards plugin;
        public static 
    Economy econ null;
        public static 
    FileConfiguration classcompleted;
     
        public 
    void onDisable() {
            
    PluginDescriptionFile pdffile this.getDescription();
            
    this.logger.info("[" pdffile.getName() + "]" " Version "
                    
    pdffile.getVersion() + " Has Been Disabled!!");
        }
     
        public 
    void onEnable() {
            
    PluginDescriptionFile pdffile this.getDescription();
            
    this.logger.info("[" pdffile.getName() + "]" " Version "
                    
    pdffile.getVersion() + " Has Been Enabled!");
            if (!
    setupEconomy()) {
                
    this.logger.severe("CANNOT SETUP VAULT ECONOMY!");
                }
            
    loadYamls();
        }
       
        public 
    void saveYamls() {
            try {
                
    completed.save(file);
            } catch (
    IOException e) {
                
    e.printStackTrace();
            }
        }
       
        public 
    void loadYamls() {
            try {
                
    completed.load(file);
            } catch (
    Exception e) {
                
    e.printStackTrace();
            }
        }
       
        private 
    boolean setupEconomy() {
            if (
    getServer().getPluginManager().getPlugin("Vault") == null) {
                return 
    false;
            }
            
    RegisteredServiceProvider<Economyrsp getServer().getServicesManager().getRegistration(Economy.class);
            if (
    rsp == null) {
                return 
    false;
            }
            
    econ rsp.getProvider();
            return 
    econ != null;
        }
       
        @
    EventHandler(priority EventPriority.NORMAL)
        public 
    void onPlayerJoin(PlayerJoinEvent event) {
            
    Player player event.getPlayer();
            
    String name player.getName();
           
            if(
    player.hasPermission("Quantumrewards.iron") && !this.completed.contains(name)) {
                
    this.completed.set("Donators." player.getName(), 0);
                
    saveYamls();
            }
        }
     
        public 
    boolean onCommand(CommandSender senderCommand cmd,
                
    String commandLabelString[] args) {
            
    Player player = (Playersender;
            
    String pbal sender.getName();
            if (
    commandLabel.equalsIgnoreCase("donorkit")) {
                if (
    args.length == 0) {
     
                    
    // Command Menu
                    
    player.sendMessage("Test");
                }
                else if (
    args.length >= 1) {
     
                    if (
    args.length != 1) {
     
                        
    player.sendMessage(ChatColor.DARK_RED "Usage: /donorkit reward");
     
                    }
                    if(
    args.length == 1) {
                        if(
    args[0].equalsIgnoreCase("reward")) {
                           
                    if (
    player.hasPermission("Quantumrewards.iron")) {
     
                        
    ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK1);
                        
    ItemStack iron = new ItemStack(Material.IRON_BLOCK5);
                        
    ItemStack copper = new ItemStack(2245);
                        
    ItemStack tin = new ItemStack(2245, (short1);
                        
    PlayerInventory pi player.getInventory();
                        
    pi.addItem(diamond);
                        
    pi.addItem(iron);
                        
    pi.addItem(copper);
                        
    pi.addItem(tin);
                        
    econ.depositPlayer(pbal100000);
                        
    double balance econ.getBalance(pbal);
                        
    player.sendMessage(ChatColor.GREEN "You now have $" balance);
                    }
     
                    if (
    player.hasPermission("Quantumrewards.gold")) {
                       
                        
    ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK5);
                        
    ItemStack iron = new ItemStack(Material.IRON_BLOCK15);
                        
    ItemStack copper = new ItemStack(22415);
                        
    ItemStack tin = new ItemStack(22415, (short1);
                        
    ItemStack rs = new ItemStack(231320);
                        
    PlayerInventory pi player.getInventory();
                        
    pi.addItem(diamond);
                        
    pi.addItem(iron);
                        
    pi.addItem(copper);
                        
    pi.addItem(tin);
                        
    pi.addItem(rs);
                        
    econ.depositPlayer(pbal300000);
                        
    double balance econ.getBalance(pbal);
                        
    player.sendMessage(ChatColor.GREEN "You now have $" balance);
                    }
     
                    if (
    player.hasPermission("Quantumrewards.diamond")) {
                       
                            
    ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK15);
                        
    ItemStack iron = new ItemStack(Material.IRON_BLOCK30);
                        
    ItemStack copper = new ItemStack(22430);
                        
    ItemStack tin = new ItemStack(22430, (short1);
                        
    ItemStack rs = new ItemStack(231640);
                        
    PlayerInventory pi player.getInventory();
                        
    pi.addItem(diamond);
                        
    pi.addItem(iron);
                        
    pi.addItem(copper);
                        
    pi.addItem(tin);
                        
    pi.addItem(rs);
                        
    econ.depositPlayer(pbal1000000);
                        
    double balance econ.getBalance(pbal);
                        
    player.sendMessage(ChatColor.GREEN "You now have $" balance);
                    }
     
                    if (
    player.hasPermission("Quantumrewards.elite")) {
                       
                        
    ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK25);
                        
    ItemStack iron = new ItemStack(Material.IRON_BLOCK50);
                        
    ItemStack copper = new ItemStack(22450);
                        
    ItemStack tin = new ItemStack(22450, (short1);
                        
    ItemStack rs = new ItemStack(2311280);
                        
    ItemStack ns = new ItemStack(301481, (short27);
                        
    PlayerInventory pi player.getInventory();
                        
    pi.addItem(diamond);
                        
    pi.addItem(iron);
                        
    pi.addItem(copper);
                        
    pi.addItem(tin);
                        
    pi.addItem(rs);
                        
    pi.addItem(ns);
                        
    econ.depositPlayer(pbal1750000);
                        
    double balance econ.getBalance(pbal);
                        
    player.sendMessage(ChatColor.GREEN "You now have $" balance);
                    }
     
                    if (
    player.hasPermission("Quantumrewards.boss")) {
     
                        
    ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK25);
                        
    ItemStack iron = new ItemStack(Material.IRON_BLOCK50);
                        
    ItemStack copper = new ItemStack(22450);
                        
    ItemStack tin = new ItemStack(22450, (short1);
                        
    ItemStack rs = new ItemStack(2311280);
                        
    ItemStack ns = new ItemStack(301481, (short27);
                        
    PlayerInventory pi player.getInventory();
                        
    pi.addItem(diamond);
                        
    pi.addItem(iron);
                        
    pi.addItem(copper);
                        
    pi.addItem(tin);
                        
    pi.addItem(rs);
                        
    pi.addItem(ns);
                        
    econ.depositPlayer(pbal1750000);
                        
    double balance econ.getBalance(pbal);
                        
    player.sendMessage(ChatColor.GREEN "You now have $" balance);
                    }
     
                    if (
    player.hasPermission("Quantumrewards.vip")) {
     
                        
    ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK5);
                        
    ItemStack iron = new ItemStack(Material.IRON_BLOCK15);
                        
    ItemStack copper = new ItemStack(22415);
                        
    ItemStack tin = new ItemStack(22415, (short1);
                        
    ItemStack rs = new ItemStack(231320);
                        
    PlayerInventory pi player.getInventory();
                        
    pi.addItem(diamond);
                        
    pi.addItem(iron);
                        
    pi.addItem(copper);
                        
    pi.addItem(tin);
                        
    pi.addItem(rs);
                        
    econ.depositPlayer(pbal300000);
                        
    double balance econ.getBalance(pbal);
                        
    player.sendMessage(ChatColor.GREEN "You now have $" balance);
                    }
                    }
                    }
                }
            }
     
            return 
    false;
        }
     
    }
    Sorry for messy code, I'm still very new to Java :D Once I'm through this and a few other needed plugins, I'll be working on learning how to set up/organize plugins.
     
  6. Offline

    pzxc

    the error is on line 59 which if i'm not mistaken is: completed.load(file);

    So either completed is null or file is null when it tries to run that

    Maybe try moving your initialization of completed and file to onEnable, just before loadYamls() is called
     
Thread Status:
Not open for further replies.

Share This Page