O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatting Messages

Problem

Messages may need to be formatted differently in different languages.

Solution

Use a MessageFormat object.

Discussion

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required