views:

418

answers:

5

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."

+5  A: 

Yes, using the MessageFormat class.

You would do the following:

String pattern = bundle.getString("example.dynamicresource");
String message = MessageFormat.format(pattern, accountCount);
David Sykes
+2  A: 

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.

skaffman
A: 

I don't believe ResourceBundle can do that itself, but String can:

String.format(bundle.getString("example.dynamicresource"), accountCount);
tom
+1  A: 

There are various ways, depending on the view technology you're using. If you're using "plain vanilla" Java (e.g. Swing), then use MessageFormat API as answered before. If you're using a webapplication framework (which is true, if I judge your question history here correctly), then the way depends on the view technology and/or MVC framework you're using. If it is for example "plain vanilla" JSP, then you can use JSTL fmt:message for this.

<fmt:message key="example.dynamicresource">
    <fmt:param value="${bean.accountCount}">
</fmt:message>

If it is for example JSF, you can use h:outputFormat for this.

<h:outputFormat value="#{bundle['example.dynamicresource']}">
    <f:param value="#{bean.accountCount}">
</h:outputFormat>

Best place is to just consult the documentation of the technology/framework you're using (or to tell it here so that we can give better suited and more detailed answers).

BalusC
+1  A: 

Struts have a nice util called MessageResources which does exactly what you ask for....

e.g.

MessageResources resources = getResources(request, "my_resource_bundle"); // Call your bundle exactly like ResourceBundle.getBundle() method
resources.getMessage("example.dynamicresource",accountCount,param2,...);

Limitation It only allows maximum of 3 parameters (i.e. resource attribute, param1, ..., param3).

I suggest using MessageFormat (if you want to use more than 3 parameter values) as suggested by David Sykes.

PS the getResources method is available only in the Struts Action class.

The Elite Gentleman