Saving YAML Files

Discussion in 'Spigot Plugin Development' started by KeithDoesNothing, Jun 4, 2016.

  1. Hi, I need help with this. I'm not sure if this code is correct. This code should create a yml file with the following fields: world, spawnloc (this is an empty stringlist), playermax, time and ready. However, when I try to run this, it creates an empty yml file instead. I want to know what's wrong with this.

    Code (Text):
                String newmap = arg3[1];
                File mapfolder = new File(Bukkit.getServer().getPluginManager().getPlugin("CakeEater").getDataFolder(), File.separator + "Maps");
                File f = new File(mapfolder, File.separator + newmap + ".yml");
                FileConfiguration mapData = new YamlConfiguration();
               
                if (!f.exists()) {
                    try {
                        mapData.addDefault("world", "");
                        mapData.addDefault("spawnloc", locs);
                        mapData.addDefault("playermax", 0);
                        mapData.addDefault("time", 0);
                        mapData.addDefault("ready", false);
                        mapData.save(f);
                    } catch (IOException err) {
                        p.sendMessage(ChatColor.RED + "File Error!");
                        return true;
                    }
                }
     
  2. Inkzzz

    Resource Staff

    You're trying to add defaults and save a file to a file that is non-existent.
     
    • Informative Informative x 1
  3. When you check if it doesn't exist, you save the file, maybe try to create it?
    if(!(f.exists()) {
    mapData.createNewFile(f);
    }
     
  4. ayyyyyyy
     
    • Like Like x 1
  5. It doesn't work though. I also tried creating a new file using:
    Code (Text):
    f.createNewFile();
    But still, it creates a blank yml file.
     
  6. Try this ;-)

    Code (Java):
    public void createConfig(){
         
            File file = new File(plugin.getDataFolder()+File.separator+"/config/config.yml");
            YamlConfiguration yamlFile;
            yamlFile = YamlConfiguration.loadConfiguration(file);
            yamlFile.options().header("Config File");
           
            yamlFile.addDefault("world", "");
            yamlFile.addDefault("spawnloc", locs);
            yamlFile.addDefault("playermax", 0);
            yamlFile.addDefault("time", 0);
            yamlFile.addDefault("ready", false);

            yamlFile.options().copyDefaults(true);
         
            try {
                yamlFile.save(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());
            }
         
        }
     
    • Like Like x 1
  7. Works fine, thanks