第一个例子使用静态的方法 MessageFormat.format
,它在内部创建一个只使用一次的 MessageFormat
:
int planet = 7; String event = "a disturbance in the Force"; String result = MessageFormat.format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", planet, new Date(), event);
输出为:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
下面的例子创建了一个可以重复使用的 MessageFormat
实例:
int fileCount = 1273; String diskName = "MyDisk"; Object[] testArgs = {new Long(fileCount), diskName}; MessageFormat form = new MessageFormat( "The disk /"{1}/" contains {0} file(s)."); System.out.println(form.format(testArgs));
不同 fileCount
值的输出:
The disk "MyDisk" contains 0 file(s). The disk "MyDisk" contains 1 file(s). The disk "MyDisk" contains 1,273 file(s).
对于更复杂的模式,可以使用 ChoiceFormat
来生成正确的单数和复数形式:
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); int fileCount = 1273; String diskName = "MyDisk"; Object[] testArgs = {new Long(fileCount), diskName}; System.out.println(form.format(testArgs));
不同的 fileCount
值的输出:
The disk "MyDisk" contains no files. The disk "MyDisk" contains one file. The disk "MyDisk" contains 1,273 files.
=============================================================
- MessageFormat 使用以下形式的模式:
- MessageFormatPattern:
- String
- MessageFormatPattern FormatElement String
- FormatElement:
- { ArgumentIndex }
- { ArgumentIndex , FormatType }
- { ArgumentIndex , FormatType , FormatStyle }
- FormatType: one of
- number date time choice
- FormatStyle:
- short
- medium
- long
- full
- integer
- currency
- percent
- SubformatPattern
- String:
- StringPartopt
- String StringPart
- StringPart:
- ''
- ' QuotedString '
- UnquotedString
- SubformatPattern:
- SubformatPatternPartopt
- SubformatPattern SubformatPatternPart
- SubFormatPatternPart:
- ' QuotedPattern '
- UnquotedPattern
MessageFormat 使用以下形式的模式:
MessageFormatPattern:
String
MessageFormatPattern FormatElement String
FormatElement:
{ ArgumentIndex }
{ ArgumentIndex , FormatType }
{ ArgumentIndex , FormatType , FormatStyle }
FormatType: one of
number date time choice
FormatStyle:
short
medium
long
full
integer
currency
percent
SubformatPattern
String:
StringPartopt
String StringPart
StringPart:
''
' QuotedString '
UnquotedString
SubformatPattern:
SubformatPatternPartopt
SubformatPattern SubformatPatternPart
SubFormatPatternPart:
' QuotedPattern '
UnquotedPattern
在 String 中,"''" 表示单引号。QuotedString 可以包含除单引号之外的任意字符;围绕的单引号被移除。UnquotedString 可以包含除单引号和左花括号之外的任意字符。因此,格式化后消息字符串为 "'{0}'" 的字符串可以写作 "'''{'0}''" 或 "'''{0}'''"。
在 SubformatPattern 中,应用了不同的规则。QuotedPattern 可包含除单引号之外的任意字符,但不移除围绕的单引号,因此它们可以由子格式解释。例如,"{1,number,$'#',##}" 将产生一个带井号的数字格式,结果如:"$#31,45"。 UnquotedPattern 可以包含除单引号之外的任意字符,但其中的花括号必须成对出现。例如,"ab {0} de" 和 "ab '}' de" 是有效的子格式模式,而 "ab {0'}' de" 和 "ab } de" 则是无效的。