Java Cookbook
How to combine dynamic and static data
Problem:
You want to combine dynamic values with your static resource files.
Solution:
There are many situations where part of a sentence comes from a dynamic source, or is provided by the user. Obviously translatng a sentence for every possible scenario is not an option. Thankfully Java provides a solution for this situation. It is called MessageFormat.
A message format is a way of replacing variables in a sentence in a locale sensitive manner.
A simple message format:
String msg = "Hello, {0}. My name is {1}.";
Object[] args = {"John", "Tom"};
System.out.println(MessageFormat.format(msg, args));
You can also specify formatting information with the variables, and they will be formatted in a locale appropriate manner.
//In the message we specify a format style and type.
//Type can be specified as number,time, date, or choice.
//Style can be short, medium, long, or full for date and time types. It can be
//integer, currency, or percent for number types.
String msg = "Today is {0,date,full}. I have {1,number,currency} in my wallet";
//The arguments to replace the values are specifed as elements in an object array
Object[] args = {new Date(), 1876};
//Create a MessageFormat instance
MessageFormat mf = new MessageFormat(msg,new Locale("fr","FR"));
//call format passing in the argument array
System.out.println(mf.format(args));
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search