Skip to content

Instantly share code, notes, and snippets.

@ScRaizer
Last active November 27, 2016 19:53
Show Gist options
  • Save ScRaizer/9a04fe77ee16e050c0ce to your computer and use it in GitHub Desktop.
Save ScRaizer/9a04fe77ee16e050c0ce to your computer and use it in GitHub Desktop.
Example java class in creating multiple config files on bukkit.
package me.ruptur.multipledatafiles;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import org.bukkit.Bukkit;
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.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
public class MultipleDataFiles extends JavaPlugin implements Listener{
private Plugin plugin;
private File datafile;
private FileConfiguration data;
private File playerfile;
private FileConfiguration player;
public void onEnable() {
this.plugin = this;
this.getServer().getPluginManager().registerEvents(this, this);
try {
getFiles();
} catch (IOException ex) {
log(Level.SEVERE, "[MultipleDataFiles] Was unable to create files!");
log(Level.INFO, "[MultipleDataFiles] Delete data file and try again");
this.plugin.getPluginLoader().disablePlugin(this.plugin);
}
for (Player p : this.getServer().getOnlinePlayers()) {
loadPlayer(p.getName());
}
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
loadPlayer(e.getPlayer().getName());
}
private void loadPlayer(String name) {
setValue(player, name + ".name", name);
if (data.getInt("loaded count") == 0) {
setValue(data, "loaded count", 0);
}
setValue(data, "loaded count", data.getInt("loaded count") + 1);
}
private void getFiles() throws IOException {
if (!plugin.getDataFolder().exists) plugin.getDataFolder().mkdir();
datafile = new File(plugin.getDataFolder(), "data.yml");
playerfile = new File(plugin.getDataFolder(), "players.yml");
if (!datafile.exists()) datafile.createNewFile();
if (!playerfile.exists()) playerfile.createNewFile();
data = YamlConfiguration.loadConfiguration(datafile);
player = YamlConfiguration.loadConfiguration(playerfile);
}
private void log(Level level, String message) {
Bukkit.getLogger().log(level, message);
}
private void setValue(FileConfiguration c, String path, Object value) {
c.set(path, value);
trysave(c);
}
private void trysave(FileConfiguration c) {
try {
c.save(file(c));
} catch (IOException e) {
log(Level.SEVERE, "[MultipleDataFiles] Was unable to save " + c.getName() + " file");
}
}
private File file(FileConfiguration c) {
return c.getKeys(false) == YamlConfiguration.loadConfiguration(datafile) ? datafile : playerfile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment