What is the best way to store game configuration parameters in java

I write a small java game and save the global settings of the game in the class structure, as shown below:

public class Globals {
    public static int tileSize = 16;
    public static String screenshotDir = "..\\somepath\\..";
    public static String screenshotNameFormat = "gameNamexxx.png";
    public static int maxParticles = 300;
    public static float gravity = 980f;
    // etc
}

While this is very convenient for work, I would like to know if this is a recognized template.

+5
source share
2 answers

Save it in a file .properties.

config.properties

tile.size=16
screenshot.dir=..\\somepath\\..

Reading

// Make sure this happens only the first time you start your application
Properties properties = new Properties();
// You can use FileInputStream, ClassLoader.getResourceAsStream or a reader too
properties.load(...)

Using

int tileSize = Integer.valueOf(properties.getProperty("tile.size"));
String screenshotDir = properties.getProperty("screenshot.dir");

To simplify and save minimal changes, you can also do something like this:

public class Globals {
    private static final Properties properties = new Properties();

    static {
        // do the loading here
    }

    public static final int TILE_SIZE = 
        Integer.valueOf(properties.getProperty("tile.size"));
    public static final String SCREENSHOT_DIR = 
        properties.getProperty("screenshot.dir");
    // etc
}
+10
source

If this is a really small application, it will be executed. This is not ideal, but it makes no sense to complicate too much on a small scale.

But read these values ​​from the properties file.

+1
source

All Articles