读书人

ResourceBundle跟Properties

发布时间: 2012-10-08 19:54:56 作者: rapoo

ResourceBundle和Properties
Class?TestLoad?{
ResourceBundle跟Properties???????????public?static?void?main(?String[]?argv)?{
ResourceBundle跟Properties?????????????????????InputStream?is?=?TestLoad.class.getResourceAsSteam("myprops.properties");
ResourceBundle跟Properties?????????????????????Properties?p?=?new?Properties();
ResourceBundle跟Properties?????????????????????p.load(is);
ResourceBundle跟Properties?????????????????????System.out.println(p.get("MAIL_SERVER_HOSTNAME"));
ResourceBundle跟Properties???????????}
ResourceBundle跟Properties}
ResourceBundle跟Properties?? System.out.println(??"myValue will use the default value: " + myValue);
?}
}
?ResourceBundle bundle = ResourceBundle
??.getBundle(PROPERTIES_FILE_NAME, Locale.ENGLISH);
这行代码初始化了一个ResourceBundle,Locale.ENGLISH用于指明本地化情况,因此会从"property_en.properties"中去读取配置项。如果是Locale.CHINA,则会从property_zh.properties中读取。这种机制使得程序的本地化变得简单。
?myName = bundle.getString(MY_NAME_KEY).trim();
这行代码读入配置文件中名为"name"的变量的值,并赋给静态变量myName。
此外这段代码还包含了例外处理,当读取失败的时候,配置项会使用缺省值。
这样,该类就通过ResourceBundle读取外存上的配置文件对数据进行了配置。

property_en.properties文件的内容如下
# properties sample
#
name=sega
value=100

其中以'#'开头的行为注释,ResourceBundle在遇到这些行的时候会忽略掉。

以下为完整的测试代码:

public class TestResourceBundle {
?public static final String PROPERTIES_FILE_NAME = "property";
?public static final String MY_NAME_KEY = "name";
?public static final String MY_VALUE_KEY = "value";
?
?private static String myName;
?private static String myValue;
?static {
?? try {
???? ResourceBundle bundle = ResourceBundle
??.getBundle(PROPERTIES_FILE_NAME, Locale.ENGLISH);
???? myName = bundle.getString(MY_NAME_KEY).trim();
???? myValue = bundle.getString(MY_VALUE_KEY).trim();
?? }
?? catch(Exception ex) {
??System.err.println(??? "[Property]:Can't Load property.properties");
??myName = "default name";
??myValue = "default value";
??System.out.println(??? "myName will use the default value: " + myName);
??System.out.println(??? "myValue will use the default value: " + myValue);
?? }
?}
?
?public void print() {
??System.out.println("My name is: " + myName);
??System.out.println("My value is: " + myValue);
?}
?public static void main(String[] args) {
??TestResourceBundle test = new TestResourceBundle();
??test.print();
?}
}

?

?

读书人网 >编程

热点推荐