mko
mko

Reputation: 22064

How can I use parameters in a messages.properties file?

In this question, it points out, It's possible to have something like:

message.myMessage = This message is for {0} in {1}

But I don't know how to pass parameter to it

MESSAGES.getString("message.myMessage", "foor", "bar")

but unfortunately getString can't know take other parameters Any idea?

Upvotes: 23

Views: 64393

Answers (3)

ersi_n
ersi_n

Reputation: 1

You can use a String Array.

String[] params = new String[2]; 
params[0] = "This is your text including parameters";
params[1] = "This is your second text including parameters";

If you are using JSF, pass Array to the text this way from your backing bean as a warning text :

JsfUtil.addWarn("A_MSG_TITLE_IN_PROPERTIES_FILE", params);

And insert this line to your local properties file:

A_MSG_TITLE_IN_PROPERTIES_FILE = Hello {0} and {1} 

So, output will be :

Hello This is your text including parameters and This is your second text including parameters

Upvotes: 0

vhunsicker
vhunsicker

Reputation: 539

Try out this one:

String message = "This message is for {0} in {1}.";
String result = MessageFormat.format(message, "me", "the next morning");
System.out.println(result);

(java.text.MessageFormat;)

Or in JSF:

<h:outputFormat value="This message is for {0} in {1}.">
    <f:param value="me">
    <f:param value="the next morning">
</h:outputFormat>

Upvotes: 13

pmorken
pmorken

Reputation: 784

I'm guessing you're thinking of MessageFormat? If so, it's just this:

String s = MessageFormat.format("This message is for {0} in {1}", "foo", "bar");

Or from properties:

Properties p = new Properties();
p.setProperty("messages.myMessage", "This message is for {0} in {1}");
String s = MessageFormat.format(
    p.getProperty("messages.myMessage"), "foo", "bar");

Upvotes: 33

Related Questions