Recipe 15.10 Formatting Messages


Messages may need to be formatted differently in different languages.


Use a MessageFormat object.


In English, for example, we say "file not found." But in other languages the word order is different: the word for "not found" might need to precede the word for "file." Java provides for this using the MessageFormat class. Suppose we want to format a message as follows:

$ java MessageFormatDemoIntl At 3:33:02 PM on 01-Jul-00, myfile.txt could not be opened. $ java -Duser.language=es MessageFormatDemoIntl A 3:34:49 PM sobre 01-Jul-00, no se puede abrir la fila myfile.txt. $

The MessageFormat in its simplest form takes a format string with a series of numeric indexes and an array of objects to be formatted. The objects are inserted into the resulting string, where the given array index appears. Here is a simple example of a MessageFormat in action:

import java.text.*; public class MessageFormatDemo {     static Object[] data = {             new java.util.Date( ),             "myfile.txt",             "could not be opened"     };     public static void main(String[] args) {         String result = MessageFormat.format(             "At {0,time} on {0,date}, {1} {2}.", data);         System.out.println(result);     } }

But we still need to internationalize this, so we'll add some lines to our widget's properties files. In the default (English) version:

# These are for MessageFormatDemo # filedialogs.cantopen.string=could not be opened filedialogs.cantopen.format=At {0,time} on {0,date}, {1} {2}.

In the Spanish version, we'll add these lines:

# These are for MessageFormatDemo # filedialogs.cantopen.string=no se puede abrir la fila filedialogs.cantopen.format=A {0,time} sobre {0,date}, {2} {1}.

Then MessageFormatDemo still needs to have a ResourceBundle and get both the format string and the message from the bundle. Here is MessageFormatDemoIntl :

import java.text.*; import java.util.*; public class MessageFormatDemoIntl {     static Object[] data = {             new Date( ),             "myfile.txt",             null     };     public static void main(String[] args) {         ResourceBundle rb = ResourceBundle.getBundle("Widgets");         data[2] = rb.getString("filedialogs.cantopen.string");         String result = MessageFormat.format(             rb.getString("filedialogs.cantopen.format"), data);         System.out.println(result);     } }

MessageFormat is more complex than this; see the Javadoc page for more details and examples.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: