|
| 1 | +package lol.gito.pingremote.config; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import com.google.gson.GsonBuilder; |
| 5 | + |
| 6 | +import java.io.File; |
| 7 | +import java.io.FileReader; |
| 8 | +import java.io.PrintWriter; |
| 9 | + |
| 10 | +public class ConfigBuilder<T> { |
| 11 | + private final Class<T> clazz; |
| 12 | + private final String path; |
| 13 | + |
| 14 | + private ConfigBuilder(Class<T> clazz, String path) { |
| 15 | + this.clazz = clazz; |
| 16 | + this.path = path; |
| 17 | + } |
| 18 | + |
| 19 | + public static <T> T load(Class<T> clazz, String path) { |
| 20 | + return new ConfigBuilder<>(clazz, path)._load(); |
| 21 | + } |
| 22 | + |
| 23 | + public T _load() { |
| 24 | + Gson gson = new GsonBuilder() |
| 25 | + .disableHtmlEscaping() |
| 26 | + .setPrettyPrinting() |
| 27 | + .create(); |
| 28 | + |
| 29 | + T config = gson.fromJson("{}", clazz); |
| 30 | + File configFile = new File("config/" + path + ".json"); |
| 31 | + configFile.getParentFile().mkdirs(); |
| 32 | + |
| 33 | + if (configFile.exists()) { |
| 34 | + try (FileReader fileReader = new FileReader(configFile)) { |
| 35 | + config = gson.fromJson(fileReader, clazz); |
| 36 | + } catch (Exception e) { |
| 37 | + System.out.println("Error reading config file"); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + try (PrintWriter pw = new PrintWriter(configFile)) { |
| 42 | + gson.toJson(config, pw); |
| 43 | + } catch (Exception e) { |
| 44 | + System.out.println("Error writing config file"); |
| 45 | + } |
| 46 | + |
| 47 | + return config; |
| 48 | + } |
| 49 | +} |
| 50 | + |
0 commit comments