Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java resource bundle formatting with out commas

I have a webservice implementation which validates the request and writes an error message in the response. The response is not in the desired format.

The error message template is in a resource bundle property file.

...
key=Plant name {0}  Plant Id {1}.
...

This is the error message I get after the validation.

Plant name PLANT1  Plant Id 9,905,005.

But desired output is with out commas for the numeric variable.

Plant name WPLANT  Plant Id 9905005.

Here is the code I have.

private String getErrorMessage(String messageKey, Object... args) {
    ResourceBundle messages = ResourceBundle.getBundle("ErrorMessageResourceBundle");
    MessageFormat formatter = new MessageFormat("");
    formatter.applyPattern(messages.getString(messageKey));
    String output = formatter.format(args);
    return output;
}

I am calling this method with the key and the variables as below.

...
getErrorMessage(key,"PLANT1",9905005)
...

How do I change this code to get the desired output? I prefer a method doesn't contain %s, %d since then I lose the ability to change the order of the variables in my error message in the property file.

like image 994
ravindrab Avatar asked Sep 12 '25 04:09

ravindrab


1 Answers

You can use subformat pattern. Example:

MessageFormat formatter = new MessageFormat("{0} {1,number,###0}");

So the code would be like this:

private String getErrorMessage(String messageKey, Object... args) {
    ResourceBundle messages = ResourceBundle.getBundle("ErrorMessageResourceBundle");
    MessageFormat formatter = new MessageFormat("{0} {1,number,###0}");
    formatter.applyPattern(messages.getString(messageKey));

    String output = formatter.format(args);
    return output;
}

Read Oracle's documentation about SubFormatPattern here: http://docs.oracle.com/javase/6/docs/api/java/text/MessageFormat.html#patterns