`
```
/** * 讀取資源文件工具類 * @author liyang * 2017年5月19日 */public class ResourcesUtil implements Serializable{private static final long serialVersionUID = -9217951614629363385L;/** * 系統(tǒng)語(yǔ)言環(huán)境款青,默認(rèn)為中文zh */public static final String LANGUAGE = "zh";/** * 系統(tǒng)國(guó)家環(huán)境尽爆,默認(rèn)為中國(guó)CN */public static final String COUNTRY = "CN";private static Locale getLocale() {Locale locale = new Locale(LANGUAGE, COUNTRY);return locale;} /** * 根據(jù)語(yǔ)言吸申、國(guó)家亦歉、資源文件名和key名字獲取資源文件值 * @param baseName 資源文件名 * @param language 語(yǔ)言 * @param country? 國(guó)家 * @param section? key名字 * @return 值 */private static String getProperties(String baseName, String section) {String retValue = "";try {Locale locale = getLocale();ResourceBundle rb = ResourceBundle.getBundle(baseName, locale);retValue = (String) rb.getObject(section);} catch (Exception e) {e.printStackTrace();}return retValue;}/** * 通過(guò)key從資源文件讀取內(nèi)容 * @param fileName 資源文件名 * @param key 索引 * @return 索引對(duì)應(yīng)的內(nèi)容 */public static String getValue(String fileName,String key) {return getProperties(fileName, key);}/** * 獲取資源文件下所有的索引名 * @param baseName 資源文件名 * @return */public static ListgetKeyList(String baseName) {Locale locale = getLocale();ResourceBundle rb = ResourceBundle.getBundle(baseName,locale);Listreslist = new ArrayList();Setkeyset = rb.keySet();for (Iteratorit = keyset.iterator(); it.hasNext();) {
String lkey = it.next();
reslist.add(lkey);
}
return reslist;
}
/**
* 通過(guò)key從資源文件讀取內(nèi)容,并格式化
*
* @param fileName
*? ? ? ? ? ? 資源文件名
*
* @param key
*? ? ? ? ? ? 索引
*
* @param objs
*? ? ? ? ? ? 格式化參數(shù)
*
* @return 格式化后的內(nèi)容
*/
public static String getValue(String fileName, String key, Object[] objs) {
String pattern = getValue(fileName, key);
String value = MessageFormat.format(pattern, objs);
return value;
}
public static void main(String[] args) {
System.out.println(getValue("resources.messages", "105", null));
//信息格式化肪获,如果資源中有{}的參數(shù)則需要使用MessageFormat格式化馍悟,Object[]為傳遞的參數(shù),數(shù)量根據(jù)資源文件中的{}個(gè)數(shù)決定
// System.out.println(getValue("resources.messages", "102", new Object[]{100,200}));
}
}
```