How to make a parametric configuration file?

152 views Asked by At

I have a question about configuration files. Is it possible to create a file.properties in java (example with Apache Commons Configuration) as:

name = tom
surname = donald
free string = my favourite color is + paramFromJavaCode

where paramFromJavaCode is dinamically set from Java code? I hope I was clear, thank you.

2

There are 2 answers

3
Jazzepi On BEST ANSWER

Assuming you're trying to create a .properties file programmatically you can do it this way. I added a section on how to add something to the marmot string. That's pretty basic Java string manipulation though!

public class WritePropertiesFile {
    public static void main(String[] args) {

        String customString = " are great!";

        try {
            Properties properties = new Properties();
            properties.setProperty("favoriteAnimal", "marmot" + customString);
            properties.setProperty("favoriteContinent", "Antarctica");
            properties.setProperty("favoritePerson", "Nicole");

            File file = new File("test2.properties");
            FileOutputStream fileOut = new FileOutputStream(file);
            properties.store(fileOut, "Favorite Things");
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Which will output

#Favorite Things
#Sat Feb 24 00:10:53 PST 2007
favoriteContinent=Antarctica
favoriteAnimal=marmot are great!
favoritePerson=Nicole
0
DontRelaX On

you can create it like:

free string = my favourite color is %s

and later in java code:

propval = String.format(propval, paramFromJavaCode);

for this line.