Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do resource bundles in Java support runtime string substitution?

Can you do the following with a Java ResourceBundle?

In the properties file...

example.dynamicresource=You currently have {0} accounts. 

At runtime...

int accountAcount = 3; bundle.get("example.dynamicresource",accountCount,param2,...); 

To give a result of

"You currently have 3 accounts."

like image 274
benstpierre Avatar asked Mar 15 '10 22:03

benstpierre


People also ask

What is the use of ResourceBundle in Java?

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale.

What is ResourceBundle in spring?

Spring's application context is able to resolve text messages for a target locale by their keys. Typically, the messages for one locale should be stored in one separate properties file. This properties file is called a resource bundle. MessageSource is an interface that defines several methods for resolving messages.

Are bundles in Java?

A resource bundle is a Java . properties file that contains locale-specific data. It is a way of internationalising a Java application by making the code locale-independent.

What is ResourceBundle locale?

Commonly used methods of ResourceBundle class public static ResourceBundle getBundle(String basename, Locale locale) returns the instance of the ResourceBundle class for the specified locale. public String getString(String key) returns the value for the corresponding key from this resource bundle.


2 Answers

Not without using the MessageFormat class, such as:

String pattern = bundle.getString("example.dynamicresource"); String message = MessageFormat.format(pattern, accountCount); 
like image 113
David Sykes Avatar answered Oct 04 '22 10:10

David Sykes


On their own, ResourceBundle does not support property placeholders. The usual idea is to take the String you get from the bundle, and stick it into a MessageFormat, and then use that to get your parameterized message.

If you're using JSP/JSTL, then you can combine <fmt:message> and <fmt:param> to do this, which uses ResourceBundle and MessageFormat under the covers.

If you happen to be using Spring, then it has the ResourceBundleMessageSource which does something similar, and can be used anywhere in your program. This MessageSource abstraction (combined with MessageSourceAccessor) is much nicer to use than ResourceBundle.

like image 44
skaffman Avatar answered Oct 04 '22 08:10

skaffman