Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ResourceBundle from Java/Struts and replace expressions

If I have a Resource bundle property file:

A.properties:

thekey={0} This is a test

And then I have java code that loads the resource bundle:

ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale);
labels.getString("thekey");

How can I replace the {0} text with some value

labels.getString("thekey", "Yes!!!");

Such that the output comes out as:

Yes!!! This is a test.

There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement.

like image 594
Berlin Brown Avatar asked Dec 14 '22 06:12

Berlin Brown


2 Answers

The class you're looking for is java.text.MessageFormat; specifically, calling

MessageFormat.format("{0} This {1} a test", new Object[] {"Yes!!!", "is"});

or

MessageFormat.format("{0} This {1} a test", "Yes!!!", "is");

will return

"Yes!!! This is a test"

[Unfortunately, I can't help with the Struts connection, although this looks relevant.]

like image 199
user10544 Avatar answered Dec 15 '22 20:12

user10544


There is the class org.apache.struts.util.MessageResources with various methods getMessage, some of them take arguments to insert to the actual message.

Eg.:

messageResources.getMessage("thekey", "Yes!!!");
like image 22
Lukáš Rampa Avatar answered Dec 15 '22 20:12

Lukáš Rampa