Question

I'm trying to create a java properties file with defaults, but all the examples I have seen are for either reading to a java properties file that already exist or writing not caring about the previous contents, and don't seem to cover working with default values.

Basically what I'm trying to do is,

  1. Load a default configuration file that is bundled with the application (inside the jar file)

    #File default.properties:
    user=default
    pwd=default
    
  2. Load a customized configuration file from the application root folder if it exists.

    #File user.properties:
    user=user
    name=name
    
  3. If the customized configuration file does not exist, write a commented "do nothing" config based off of the default config bundled with the application

    #File user.properties:
    #user=default
    #pwd=default
    
  4. Combine the two configuration files, using the defaults for un-populated keys and using the new values where appropriate.

    #File app.properties:
    user=user
    pwd=default
    name=name
    

I've looked through java .properties API as well as the java Preferences API but the preferences API doesn't seem useful, as the configuration is user specific as opposed to application specific.

Was it helpful?

Solution

How about it:

File default.properties:

user=default
pwd=default

File user.properties:

pwd=user
name=user

Will be printed: {user=default, name=user, pwd=user}

class Main {
  public static void main(final String [] args) throws IOException {
    //load default properties
    final Properties defaultProp = new Properties();
    defaultProp.load(Main.class.getResourceAsStream("default.properties"));

    //load user properties
    final Properties userProp = new Properties();
    userProp.load(new FileInputStream(new File("./user.properties")));

    final Properties appProp = new Properties();

    //mix properties
    appProp.putAll(defaultProp);
    appProp.putAll(userProp);

    System.out.println(appProp);
  }  
}

java.util.Properties extends java.util.Hashtable that implements java.util.Map, so you can use all method from Map.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top