Credits for this Gist go to frankred/json-config-file.
To create a json based config you can easily use the following maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
-
Create a new class for example Config.
-
Add public member variables like you would do in any other class.
-
In case you want to set any default values to be loaded when the configuration file is missing, add a method setDefaults() where you set those values. Call this method in the constructor of the Config class.
-
Paste the following code into your class:
private static Config instance;
public static Config getInstance() {
if (instance == null) {
instance = fromDefaults();
}
return instance;
}
public static void load(File file) {
instance = fromFile(file);
// no config file found
if (instance == null) {
instance = fromDefaults();
}
}
public static void load(String file) {
load(new File(file));
}
private static Config fromDefaults() {
Config config = new Config();
return config;
}
public void toFile(String file) {
toFile(new File(file));
}
public void toFile(File file) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonConfig = gson.toJson(this);
FileWriter writer;
try {
writer = new FileWriter(file);
writer.write(jsonConfig);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Config fromFile(File configFile) {
try {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile)));
return gson.fromJson(reader, Config.class);
} catch (FileNotFoundException e) {
return null;
}
}
@Override
public String toString() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
Now you're able to call the methods
save(String file)
andsave(File file)
to save your configuration to a file.
Loading works with calling the methods
load(String file)
orload(File file)
. After loading the member variables will be set.