Skip to content

Instantly share code, notes, and snippets.

@WesJD
Last active December 17, 2016 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WesJD/bc4ece6717f13b35272de7094e72676c to your computer and use it in GitHub Desktop.
Save WesJD/bc4ece6717f13b35272de7094e72676c to your computer and use it in GitHub Desktop.
Easily manage configuration files
public class FileManager {
private final JavaPlugin plugin;
private final List<ManagedFile> managedFiles = new ArrayList<>();
public FileManager(JavaPlugin plugin) {
this.plugin = plugin;
plugin.getDataFolder().mkdirs();
}
public void register(String name) throws IOException {
Validate.isTrue(get(name).isPresent(), "A ManagedFile with the name of " + name + " already exists");
managedFiles.add(new ManagedFile(plugin.getDataFolder(), name));
}
public void reload(String name) throws IOException {
get(name).get().reload();
}
public void save(String name) throws IOException {
get(name).get().save();
}
public Optional<ManagedFile> get(String name) {
return managedFiles.stream()
.filter(managedFile -> managedFile.name.equals(name))
.findFirst();
}
public static class ManagedFile {
private final String name;
private final File file;
private YamlConfiguration configuration;
ManagedFile(File dataFolder, String name) throws IOException {
this.name = name;
this.file = new File(dataFolder, name + ".yml");
if(!file.exists()) file.createNewFile();
this.configuration = YamlConfiguration.loadConfiguration(file);
}
public void reload() throws IOException {
save();
configuration = YamlConfiguration.loadConfiguration(file);
}
public void save() throws IOException {
configuration.save(file);
}
public String getName() {
return name;
}
public File getFile() {
return file;
}
public YamlConfiguration getConfiguration() {
return configuration;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment