package net.sourceforge.jtds.jdbc;
import
java.text.MessageFormat;
import java.util.Enumeration;
import
java.util.Map;
import java.util.ResourceBundle;
public final class
Messages {
private static final String DEFAULT_RESOURCE =
"net.sourceforge.jtds.jdbc.Messages"; //默認得資源
private static
ResourceBundle defaultResource; //和locale的綁定
private Messages()
{
}
public static String get(String key) {
return
get(key, null);
}
public static String get(String key, Object
param1) {
Object args[] = {param1};
return get(key,
args);
}
static String get(String key, Object param1, Object
param2) {
Object args[] = {param1, param2};
return
get(key, args);
}
private static String get(String key,
Object[] arguments) {
try {
ResourceBundle bundle =
loadResourceBundle();
String formatString =
bundle.getString(key);
// No need for any formatting if no
parameters are specified
if (arguments == null ||
arguments.length == 0) {
return
formatString;
} else {
MessageFormat formatter
= new MessageFormat(formatString);
return
formatter.format(arguments);
}
} catch
(java.util.MissingResourceException mre) {
throw new
RuntimeException("No message resource found for message property " +
key);
}
}
private static ResourceBundle
loadResourceBundle() {
if (defaultResource == null)
{
defaultResource =
ResourceBundle.getBundle(DEFAULT_RESOURCE);
}
return
defaultResource;
}
static void loadDriverProperties(Map
propertyMap, Map descriptionMap) {
final ResourceBundle bundle =
loadResourceBundle();
final Enumeration keys =
bundle.getKeys();
while (keys.hasMoreElements())
{
final String key = (String)
keys.nextElement();
final String descriptionPrefix =
"prop.desc.";
final String propertyPrefix =
"prop.";
if (key.startsWith(descriptionPrefix))
{
descriptionMap.put(key.substring(descriptionPrefix.length()),
bundle.getString(key));
}
else if
(key.startsWith(propertyPrefix))
{
propertyMap.put(key.substring(propertyPrefix.length()),
bundle.getString(key));
}
}
}
}
上面代碼中默認得綁定名為:"net.sourceforge.jtds.jdbc.Messages".其實就是以工程為根目錄,尋找文件Messages.properties.這里查找的方式和類是一樣的.比如:"net.sourceforge.jtds.jdbc.Messages",就是工程根目錄下的net/sourceforge/jtds/jdbc/下的Messages.properties文件.
這個文件定義很多的屬性,要得到只要用get方法.
注意這里的defaultResource
=
ResourceBundle.getBundle(DEFAULT_RESOURCE);沒有設定Locale值,所以文件名為Messages.properties.如果設置了Locale值的話,例如:defaultResource
= ResourceBundle.getBundle(DEFAULT_RESOURCE,
Locale.ENGLISH);那么它就會去查找文件Messages_en.properties.其他類似加后綴(Locale.CHINA是Messages_zh.properties).
關于java.text.MessageFormat類,下面通過一個例子就可以說明:
MessageFormat
mf = new MessageFormat("You have {0} messages.");
Object[] arguments =
{"no"};
System.out.println(mf.format(arguments)); //"You have no
messages."
關于String.startsWith(String prex)是測試字符串是否以prex開頭.