Parameter Substitution In Resource Bundles
If you use Java resource bundles to translate your application into several languages, it is sometimes necessary to use parameters in the properties of resource bundles. The JDK does not offer the feature to use parameters directly in resource bundles. This article shows how to use parameters in resource bundles.
Resource bundle property example
messages.properties (English):
...
itemservice.item.added = User {0} added new item {1} to group {2}.
...
messages_de.properties (German):
...
itemservice.item.added = Das Objekt {1} wurde von Benutzer {0} zur Gruppe {2} hinzugef\u00FCgt.
...
The example shows that parameters are used in English and German in different order. Therefore it is necessary to use parameters at all. To replace parameters by values, you have to use method java.text.MessageFormat.format(String text, Object … arguments). Add a small wrapper class to you project:
public class Messages { // property file is: package/name/messages.properties private static final String BUNDLE_NAME = "package.name.messages"; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static String getString(String key, Object... params ) { try { return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
You can now use the properties from the example above:
Messages.getString( "itemservice.item.added", user.getName(), item.getTitle(), group.getName());
Thanks, it was useful for me.
very useful! great article. Regards
Thanks a lot!
Thank you. This is just what I needed.
This is really useful post!
Thank you!
Thank you man.
Thanks alot.. 🙂
Thanks.
Can i use 3 parametres?
bundletext=some text {0} some text {1} some text {2}
returns
some text v1 some text v2 some text {2}
Yes you can use 3 or more parameters in your property file. Call
Messages.getString(„key“, „p1“, „p2“, „p3“ )
to get the result.
Danke schön!
Thanks! MessageFormat is the key here.
Really interesting, the only problem I had was with a long passed for example as 1348L, so I had to create an object and then .toString() in order to show correctly… because at first it was shown 1,348 .
thanks !
I have been using parameters for some time and was looking for some additional information regarding formatting of the parameters. FYI, I use dates as parameters and have the resource bundle, for example:
The start date {0,date,MM/dd/yy} must be earlier or equal to the today’s date {1,date,MM/dd/yy}
For dollar amounts:
total balance of {0,number,currency}
Very helpful, thank you 🙂