Created
January 6, 2023 21:37
-
-
Save jacg311/69b3cd93fe502663a97132e17774122f to your computer and use it in GitHub Desktop.
small config with gson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Config { | |
private static Gson GSON = new GsonBuilder().setPrettyPrinting().create(); // got a bunch of cool config options | |
int someIntValue = 5; // field where the values will be held, default value would be 5 | |
String aString = "hello world"; // lots of standard types work, you can always register new deserializers in your GSON instance. google it. | |
public static Config readConfig() { | |
Path configFile = FabricLoader.getInstance().getConfigDir().resolve("filename.json"); | |
try { | |
// read file contents and let gson construct an instance of it | |
return GSON.fromJson(Files.readString(configFile), Config.class); | |
} | |
catch (IOException e) { | |
// handle failure somehow, crash the game, use all default values, whatever | |
throw new RuntimeException(e); | |
} | |
} | |
public void writeConfig() { | |
Path configFile = FabricLoader.getInstance().getConfigDir().resolve("filename.json"); | |
try { | |
// write the config to file | |
Files.writeString(configFile, GSON.toJson(this)); | |
} | |
catch (IOException e) { | |
// handle failure somehow | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment