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

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.