學習了 Tomcat 的StringManager 類之後,學習了一下ResourceBundle類,對國際化管理又有了進一步的瞭解
通過Locale類來表示特定的地理、政治和文化地區,所以可以將屬性文件在結尾的地方加上相應的locale地區,即可顯示該地區特定的string
代碼如下:
package com.fw.resource;
import java.text.MessageFormat;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class ResourceManager {
/**
* the ResourceBundle for this ResourceManager
*/
private final ResourceBundle bundle;
private final Locale locale;
/**
* use the Single pattern
* initialize the bundle and locale
*/
private ResourceManager(String name, Locale locale) {
String bundleName = name + ".LocalStrings";
ResourceBundle bnd = null;
try {
bnd = ResourceBundle.getBundle(bundleName, locale);
} catch (MissingResourceException e) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
bnd = ResourceBundle.getBundle(bundleName, locale, cl);
} catch (MissingResourceException e1) {
//Ignore
}
}
bundle = bnd;
if(bundle!=null){
this.locale = bundle.getLocale();
} else {
this.locale = null;
}
}
public String getString(String key){
if(key == null){
String msg = " key may not have a null value";
throw new IllegalArgumentException(msg);
}
String str = null;
try {
if(bundle!=null){
str = bundle.getString(key);
}
} catch (MissingResourceException e) {
str = null;
}
return str;
}
public String getString(String key, final Object... objects) {
String value = getString(key);
if(value == null){
value = key;
}
MessageFormat mf = new MessageFormat(value);
mf.setLocale(locale);
return mf.format(objects, new StringBuffer(), null).toString();
}
/**
* identify the Locale this StringManager is associate with
*/
public Locale getLocale(){
return locale;
}
private static final Map<String, Map<Locale, ResourceManager>> managers =
new Hashtable<String, Map<Locale, ResourceManager>>();
public static final synchronized ResourceManager getManager(String packageName){
return getManager(packageName, Locale.getDefault());
}
/**
* Get ResourceManager by special packageName and locale, if the mgr is already exists,
* it will be reuse, or a new ResourceManager will be created and return;
* @param packageName
* @param locale
* @return
*/
public static final synchronized ResourceManager getManager(String packageName, Locale locale) {
Map<Locale, ResourceManager> map = managers.get(packageName);
if(map == null){
map = new Hashtable<Locale, ResourceManager>();
managers.put(packageName, map);
}
ResourceManager mgr = map.get(locale);
if(mgr == null) {
mgr = new ResourceManager(packageName, locale);
map.put(locale, mgr);
}
return mgr;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(Locale.getDefault());
System.out.println(Locale.CHINA);
ResourceManager mgr = getManager("com.fw.regex", Locale.getDefault());
String str = mgr.getString("name");
System.out.println(str);
}
}
屬性文件可以定義在某個包裏即可