I'm trying to make a Bukkit/Spigot plugin which stores user data with YML files, and I can't make a list in file that gets created when the users joins. I'm using the built in parser.
The Code:
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player p = e.getPlayer();
File f;
f = new File(getDataFolder(), "UserData/" + p.getUniqueId() + ".yml");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
FileConfiguration mapconfig = YamlConfiguration.loadConfiguration(new File(getDataFolder() + "UserData/" + p.getUniqueId() + ".yml"));
mapconfig.createSection("Mobs");
mapconfig.set("Mobs", "mob1");
Bukkit.getServer().getLogger().info("[Morph] Creating new user file " + p.getUniqueId() + "for user " + p.getName());
}
}
The files are created, but they are empty.
Mobs:
- mob1
I need the section empty. What am I doing wrong?
Updated code--------------------
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player p = e.getPlayer();
File f;
f = new File(getDataFolder(), "UserData/" + p.getUniqueId() + ".yml");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
FileConfiguration mapconfig = YamlConfiguration.loadConfiguration(new File(getDataFolder() + "UserData/" + p.getUniqueId() + ".yml"));
mapconfig.createSection("Mobs");
List<String> ListOfStrings = Arrays.asList("mob1");
mapconfig.set("Mobs", ListOfStrings);
try {
mapconfig.save(getDataFolder() + "UserData/" + p.getUniqueId() + ".yml");
} catch (IOException e1) {
e1.printStackTrace();
}
Bukkit.getServer().getLogger().info("[Morph] Creating new user file " + p.getUniqueId() + "for user " + p.getName());
}
}
You need to save the edited YAML configuration to the player's file by using
mapconfig.save(file)
in a try block after you've added all the nodes etc.If you'd like the list "Mobs" to be initially empty, leave out the
mapconfig.set("Mobs", "mob1");
line.To add elements to the "Mobs" list, you'll need to create a list of strings to add. As far as I can tell, each time you want to update the list by removing or adding another string, you need to first load the YAML file (extra step after creating the configuration) using
mapconfig.load(file)
, then get the current values (strings) in the list usingmapconfig.getStringList("Mobs")
, update the list as you like, re-set it to the "Mobs" node and save the file again (example below).And to update the list if the file already exists, for example by adding a new string.
In case something still doesn't work, here is my slightly cleaned up version of your code that worked for me.