ut, with different testArgs
output: The disk "MyDisk" contains 0 file(s).
output: The disk "MyDisk" contains 1 file(s).
output: The disk "MyDisk" contains 1,273 file(s).
For more sophisticated patterns, you can use a ChoiceFormat
to get output such as:
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}."); double[] filelimits = {0,1,2}; String[] filepart = {"no files","one file","{0,number} files"}; ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart); form.setFormatByArgumentIndex(0, fileform); Object[] testArgs = {new Long(12373), "MyDisk"}; System.out.println(form.format(testArgs)); // output, with different testArgs output: The disk "MyDisk" contains no files. output: The disk "MyDisk" contains one file. output: The disk "MyDisk" contains 1,273 files.
You can either do this programmatically, as in the above example, or by using a pattern (see {@link ChoiceFormat}for more information) as in:
form.applyPattern( "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
Note: As we see above, the string produced by a ChoiceFormat
in MessageFormat
is treated specially; occurances of '{' are used to indicated subformats, and cause recursion. If you create both a MessageFormat
and ChoiceFormat
programmatically (instead of using the string patterns), then be careful not to produce a format that recurses on itself, which will cause an infinite loop.
When a single argument is parsed more than once in the string, the last match will be the final result of the parsing. For example,
MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}"); Object[] objs = {new Double(3.1415)}; String result = mf.format( objs ); // result now equals "3.14, 3.1" objs = null; objs = mf.parse(result, new ParsePosition(0)); // objs now equals {new Double(3.1)}
Likewise, parsing with a MessageFormat object using patterns containing multiple occurances of the same argument would return the last match. For example,
MessageFormat mf = new MessageFormat("{0}, {0}, {0}"); String forParsing = "x, y, z"; Object[] objs = mf.parse(forParsing, new ParsePosition(0)); // result now equals {new String("z")}
Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
@see java.util.Locale
@see Format
@see NumberFormat
@see DecimalFormat
@see ChoiceFormat
@author Mark Davis
@stable ICU 3.0