hanze/game-client

src/main/java/nl/isygameclient/util/SettingsFileHandler.java in main
Repositories | Summary | Log | Files

SettingsFileHandler.java (1711B) download


 1package nl.isygameclient.util;
 2
 3import com.google.gson.Gson;
 4import com.google.gson.GsonBuilder;
 5import nl.isygameclient.settings.Settings;
 6
 7import java.io.FileWriter;
 8import java.io.IOException;
 9import java.nio.file.Files;
10import java.nio.file.Paths;
11
12
13/**
14 * This Class is for accessing and manipulating settings files.
15 * This class handles the loading and saving of settings data.
16 * @author A F Koens
17 */
18public abstract class SettingsFileHandler {
19    public static final String SETTINGS_FILENAME = "settings.json";
20
21
22    /**
23     * Save a settings object to a json file.
24     * @param settings a Settings object.
25     * */
26    public static void save(Settings settings) {
27        try {
28            Gson gson = new GsonBuilder()
29                    .setPrettyPrinting()
30                    .create();
31
32            FileWriter writer = new FileWriter(SETTINGS_FILENAME);
33            writer.write(gson.toJson(settings));
34            writer.close();
35        } catch (IOException e) {
36            e.printStackTrace();
37        }
38    }
39
40    /**
41     * Read a json file and loads its values into a Settings object.
42     * @return a Settings object.
43     * */
44    public static Settings load() {
45        try {
46            Gson gson = new GsonBuilder()
47                    .setPrettyPrinting()
48                    .create();
49
50            String inFile = new String(Files.readAllBytes(Paths.get(SETTINGS_FILENAME)));
51            return gson.fromJson(inFile, Settings.class);
52        } catch (IOException e) {
53            System.err.println("Could Not Load Settings File, Using Defaults Instead");
54            var defaults = new Settings();
55            save(defaults);
56            return defaults;
57        }
58    }
59}
60