**如果一個字符串中包含了多個與國際化相關的數據,可以使用MessageFormat類對這些數據進行批量處理。
例如:
At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and caused $1000000 of damage
以上字符串中包含了時間、數字、貨幣等多個與國際化相關的數據,對於這種字符串,可以使用MessageFormat類對其國際化相關的數據進行批量處理。
MessageFormat 類如何進行批量處理呢?
1.MessageFormat類允許開發人員用佔位符{0}{1}{2}…替換掉字符串中的敏感數據(即國際化相關的數據)。
2.MessageFormat類在格式化輸出包含佔位符的文本時,messageFormat類可以接收一個參數數組,以替換文本中的每一個佔位符。
package cn.test;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class MessageFormatTest {
public static void main(String[] args) {
//根據配置文件名獲取資源包的內容
ResourceBundle bundle = ResourceBundle.getBundle("message", Locale.US);
String pattern = bundle.getString("login.error");
System.out.println(pattern);
//向模版裏面佔位符添加值(username)
String value = MessageFormat.format(pattern,"username","這是傳進去的參數");
System.out.println(value);
}
}
————————————————————————–對應的資源包:
title=登錄窗口
username=用戶名
password=密碼
submit=提交
login.error = {0} is required {1}
MessageFormat
動態文件格式化.
MessageForamt可以對一個模板中的信息進行動態賦值.
1.MessageFormat使用
MessageForamt.format(String pattern,Object... params);
2.說明一下關於動態文本中的佔位符?
例如:{0} is required
1.注意佔位符只能使用{0}---{9}之間的數值.
2.關於佔們符的格式
{argumentIndex}: 0-9 之間的數字,表示要格式化對象數據在參數數組中的索引號
{argumentIndex,formatType}: 參數的格式化類型
{argumentIndex,formatType,FormatStyle}: 格式化的樣式,它的值必須是與格式化類型相匹配的合法模式、或表示合法模式的字符串。
formatType可以取的值有:number date time
formatStyle可以取的值有
number類型可以取:integer currency percent
date類型可以取的:short medium full long
time類型可以取的:short medium full long
@Test
public void fun1() {
// At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and
// caused $1000000 of damage
String msg = "At {0,time,medium} on {0,date,long}, a hurricance destroyed {1,number,integer} houses and caused {2,number,currency} of damage";
Date date = new Date();
// String value=MessageFormat.format(msg, date,99,1000000);
// System.out.println(value);
MessageFormat mf = new MessageFormat(msg, Locale.US);
String value = mf.format(new Object[] { date, 99, 1000000 });
System.out.println(value);
}
@Test
public void fun2() {
// At 12:30 pm on jul 3,1998, a hurricance destroyed 99 houses and
// caused $1000000 of damage
String msg = "At {0,time,short} on {0,date,long}, a hurricance destroyed {1,number,integer} houses and caused {2,number,currency} of damage";
Calendar c = Calendar.getInstance();
c.set(1998, 6, 3, 12, 30,0);
Date date = c.getTime();
MessageFormat mf = new MessageFormat(msg, Locale.US);
String value = mf.format(new Object[] { date, 99, 1000000 });
System.out.println(value);
}