ResourceBundle from Java / Struts and replace expressions

If I have a resource bundle properties file:

A.properties:

thekey={0} This is a test 

And then I have Java code that loads the resource package:

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

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

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

Such that the output is obtained as:

 Yes!!! This is a test. 

There are no methods that are part of the Resource Bundle to do this. Also, I'm in Struts, is there any way to use MessageProperties to replace.

+4
source share
2 answers

The class you are looking for is java.text.MessageFormat; in particular by causing

 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 connecting Struts, although this seems relevant.]

+11
source

There is an org.apache.struts.util.MessageResources class with various getMessage methods, some of which accept arguments to be inserted into the actual message.

For instance:.

 messageResources.getMessage("thekey", "Yes!!!"); 
+2
source

Source: https://habr.com/ru/post/1276719/


All Articles