Khalil Pokari
Khalil Pokari

Reputation: 171

Properties file: Use key as variable

I want to use a key defined in properties file as a variable like this:

key1= value1
key2= value2
key3= key1

I tried:

key3= {key1}

or

key3= ${key1}

But it doesn't work. Any ideas?

Upvotes: 16

Views: 47037

Answers (3)

csd
csd

Reputation: 1784

Java's built-in Properties class doesn't do what you're looking for.

But there are third-party libraries out there that do. Commons Configuration is one that I have used with some success. The PropertiesConfiguration class does exactly what you're looking for.

So you might have a file named my.properties that looks like this:

key1=value1
key2=Something and ${key1}

Code that uses this file might look like this:

CompositeConfiguration config = new CompositeConfiguration();
config.addConfiguration(new SystemConfiguration());
config.addConfiguration(new PropertiesConfiguration("my.properties"));

String myValue = config.getString("key2");

myValue will be "Something and value1".

Upvotes: 22

Saša
Saša

Reputation: 4798

.xmlEven better: use the latest Maven. You can do some neat stuff with maven. In this case you can make an .properties file with this lines in it:

key1 = ${src1.dir}
key2 = ${src1.dir}/${filename}
key3 = ${project.basedir}

in the maven's pom.xml file (placed in the root of your project) you should do something like this:

<resources>
    <resource>
        <filtering>true</filtering>
        <directory>just-path-to-the-properties-file-without-it</directory>
        <includes>
            <include>file-name-to-be-filtered</include>
        </includes>
    </resource>
</resources>

...

<properties>
    <src1.dir>/home/root</src1.dir>
    <filename>some-file-name</filename>
</properties>

That way you would have keys values changed in build time, which means that after compiling you will have this values inside your properties file:

key1 = /home/root
key2 = /home/root/some-file-name
key3 = the-path-to-your-project

compile with this line when you are in the same dir as pom.xml file: mvn clean install -DskipTests

Upvotes: 0

vandershraaf
vandershraaf

Reputation: 895

When you define the value of a key in properties file, it will be parsed as literal value. So when you define key3= ${key1}, key3 will have value of "${key1}".

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream)

I agree with csd, the plain configuration file may not be your choice. I prefer using Apache Ant ( http://ant.apache.org/ ), where you can do something like this:

<property name="src.dir" value="src"/>
<property name="conf.dir" value="conf" />

Then later when you want to use key 'src.dir', just call it something like this:

<dirset dir="${src.dir}"/>

Another good thing about using Apache Ant is you also can load the .properties file into Ant build file. Just import it like this:

<loadproperties srcFile="file.properties"/>

Upvotes: 0

Related Questions