0

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.

django
  • 153
  • 1
  • 5
  • 19
  • Are you trying to create a .properties file in Java code? – Jazzepi Nov 28 '14 at 14:51
  • I have already created it, but I don't know if that I have written is possible @Jazzepi – django Nov 28 '14 at 14:53
  • You can write anything you want to a file using normal Java operations; it's not clear what the issue is. – Dave Newton Nov 28 '14 at 14:56
  • I'd like to write a config file manually, but some string could be handled from Java code so, exists a syntax to chain parameter to string in _file.properties_? @Dave Newton – django Nov 28 '14 at 15:19

2 Answers2

0

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
Jazzepi
  • 5,259
  • 11
  • 55
  • 81
  • Ok thank you, but is it possible to set first the string "marmot" manually in config file and then chain it a string from Java code? – django Nov 28 '14 at 14:59
  • You want to add something to the "marmot" string? Like "marmot is great"? – Jazzepi Nov 28 '14 at 15:01
  • Yes. "marmot" added manully and "is great" setted from java code to getting later the string "marmot is great" @Jazzepi – django Nov 28 '14 at 15:03
0

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.

DontRelaX
  • 744
  • 4
  • 10