The i18n Cookbook - recipies for a global society

  • java cookbook
  • about the author
Home › Java Internationalization Cookbook › Resource Bundles

Java Cookbook

  • Java Internationalization Cookbook
    • Locales
    • Dates and Times
    • Numerical Systems
    • Misc
    • Resource Bundles
      • Handle plural text in a localizable manner.
      • How to combine dynamic and static data
      • Load properties from outside the classpath
      • Spell out the numeric value in a concatenated string
    • Unicode, Transliteration, and Charactersets

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));

‹ Handle plural text in a localizable manner. up Load properties from outside the classpath ›
  • messageformat
  • resourcebundle
  • Printer-friendly version
  • Add new comment

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

Google
Custom Search

Search

Tags in Tags

calendar date icu4j Java Locale number format numberformat parse spellout timezone transliteration transliterator
more tags

User login

  • Create new account
  • Request new password
  • java cookbook
  • about the author