1.消息资源类,内部的ResourceBundle对应于一个消息资源文件
import java.text.*;
import java.util.*;
public class MessageResource {
private ResourceBundle rb; //资源绑定
private ClientAppLogger logger = ClientAppLogger.getInstance();
/**
* 构造器
* @param props Properties 资源绑定
*/
public MessageResource(ResourceBundle rb) {
this.rb = rb;
}
/**
* 得到消息字符
* @param key String 键
* @return String
*/
public String getString(String key) {
try {
return rb.getString(key);
} catch (MissingResourceException ex) {
logger.error("MissingMessageResource:key=" + key);
return "undefined";
}
}
/**
* 得到消息资源
* @param key String 键
* @param args Object[] 可变消息
* @return String
*/
public String getString(String key, Object[] args) {
try {
String temp = rb.getString(key);
MessageFormat mFormat = new MessageFormat(temp);
return mFormat.format(temp, args);
} catch (MissingResourceException ex) {
logger.error("MissingMessageResource:key=" + key);
return "undefined";
}
}
}
2.消息资源工厂
import java.util.*;
public class MessageResourceFactory {
private static MessageResourceFactory factory = new MessageResourceFactory();
private Map msgResourceMap = null; //存放消息资源
private MessageResourceFactory() {
msgResourceMap = new HashMap();
}
public static MessageResourceFactory getInstance() {
return factory;
}
/**
* 创建消息资源
* @param name String 消息资源文件名
* @param locale Locale
* @return MessageResource
*/
public MessageResource createMessageResource(String fileResName, Locale locale) {
Object msgResObj = msgResourceMap.get(name);
if (msgResObj == null) {
ResourceBundle rb = ResourceBundle.getBundle(fileResName, loc);
MessageResource msgRes = new MessageResource(rb);
msgResourceMap.put(name, msgRes);
return msgRes;
} else {
return (MessageResource)msgResObj;
}
}
}
3.使用
比如:消息资源文件为
message_en_US.properties文件内容:
button.add=Add
button.update=Modify
button.delete=Delete
button.refresh=Refresh
state.success=Operation Success
state.failure=Operation Failure
message=The disk {0} contains {1} files.
message_zh_CN.properties文件内容:
button.add=/u6dfb/u52a0
button.update=/u4fee/u6539
button.delete=/u5220/u9664
button.refresh=/u5237/u65b0
state.success=/u64cd/u4f5c/u6210/u529f
state.failure=/u64cd/u4f5c/u5931/u8d25
message=The disk {0} contains {1} files.
(其中,中文文件利用了native2ascii命令进行了转化)
使用代码如下:
MessageResourceFactory factory = MessageResourceFactory.getInstance();
MessageResource res = factory.createMessageResource("message", new Locale("zh", "CN"));
String value = res.getString("button.add");
String value_args = res.getString("message", new Object[]{"C", "12"});