Can I reference another property in a properties file (use ${property}) [duplicate]
Asked Answered
T

3

55

Possible Duplicate:
How to reference another property in java.util.Properties?

look at my "file.properties":

key1= My name is
key2= ${key1} Martin !

Why when I get the value of "key2" my result is "${key1} Martin !" unlike "My name is Martin !"

=> I program in Java 6
=> I use java.util.Properties

Trapeziform answered 11/9, 2009 at 17:2 Comment(0)
L
34

You might want look at Apache Configuration,

http://commons.apache.org/configuration/

Among many features it supports is the Variable Interpolation.

Lydalyddite answered 11/9, 2009 at 17:37 Comment(1)
That's it ! name=Martin myKey=hi ${name} ! String result = new PropertiesConfiguration("myFile.properties").getString("myKey"); ====> the value of "result" is "hi Martin !"Trapeziform
M
18

What you want to do is impossible using the Java Properties class.

Property keys and values are simply Strings. No processing happens to them, so you can't refer to another value in a value.

Maybe answered 11/9, 2009 at 17:4 Comment(5)
weird. Using ANT you can do this. What's up with Java?Munitions
ANT has nothing to do with Java properties. My (limited) understanding of the under-the-hood stuff in ANT is that it's parsed. Java Properties files are simply text files that contain String keys and String values that can be loaded into memory.Maybe
It's been awhile since I looked at the source but I think ant uses org.apache.commons.configuration for it's property parsing. Don't quote me on that.Sumption
"What's up with Java?" I think you mean what's up with java.util.Properties, and the answer is that it doesn't do property expansion, nor does it claim to.Rancho
Seems like it should. But it sounds like using the Apache Configuration like ANT would be better.Munitions
B
1

Ant files are scripts; properties files are buckets of strings.

The primary purpose of properties files is to serve as string containers for translatable text. The format strings typically used in resource bundles use an index-based system. When the string is translated, the order of the parameters can be changed in translated versions of the string without needing to change the Java code.

String what = "Hello";
String who = "Martin";
System.out.println(MessageFormat.format("{0}, {1}!", what, who));
System.out.println(MessageFormat.format("{1}, {0}!", what, who));

Output:

Hello, Martin!
Martin, Hello!

For use cases like this, it would not make sense to encapsulate the functionality in the Properties class because the strings usually need data from the application. The MessageFormat class can be used to perform the substitution.

This type of formatting should not be confused with the other formatting options as specified by Formatter:

System.out.format("%s, %s!%n", what, who);
Bayles answered 11/9, 2009 at 17:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.