Skip to content

Instantly share code, notes, and snippets.

@jacg311
Created January 6, 2023 21:37
Show Gist options
  • Save jacg311/69b3cd93fe502663a97132e17774122f to your computer and use it in GitHub Desktop.
Save jacg311/69b3cd93fe502663a97132e17774122f to your computer and use it in GitHub Desktop.
small config with gson
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