随笔-16  评论-50  文章-2  trackbacks-0

摘要:大多数应用程序都可以由用户配置。配置文件是实现应用程序灵活性的一个有效手段。Hibernate、Spring等应用都需要配置文件。国际化的应用程序也是通过和Locale有关配置文件来实现的。

 

下面的内容和Java应用程序配置有关。

  • properties
    • properties文件
    • 系统信息
  • preferences

 

properties的使用

加载

Properties prop = new Properties();
prop.load(new FileInputStream("filename"));
String value = prop.getProperties("key");

 

存储

Properties prop = new Properties();
prop.setProperties("key", "value");
...
prop.store(new FileOutputStream("filename.properties"), "comments");

 

默认值

prop.getProperties("key", "default");

或者:

Properties defaultProp = new Properties();
defaultProp.setProperties("key", "value");
...

Properties prop = new Properties(defaultProp);
prop.load(new FileInputStream("filename"));
prop.getProperties("key");

 

汉字

手写的Properties文件,如果含有非ISO-8859-1的字符,就要用native2ascii.exe工具来编译了。eclipse中也有工具可以实现该功能。native2ascii的使用很简单。

 

结构化的key

font.name=Monospaced
font.size=12

 

枚举key和values

public Enumeration<?> propertyNames()

size(), keys(), values

 

XML

<properties>
    <comment>comments</comment>
    <entry key="key">value</entry>
    ... ...
</properties>

 

Properties和Hashtabel的关系?

Properties是Hashtable的子类。 这是一个坏的设计。Hashtable应当只是Properties的一个实例变量。

class Properties {
    public String getProperty(String) {...}
    public String setProperty(String, String) {...}
    ...
    private Hashtable entry;
    protected Properties defaults;
}

在Properties的API中有下面的一段话,Sun通过文档来弥补设计上的缺陷。

因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法。但强烈反对使用这两个方法,因为它们允许调用方插入其键或值不是 Strings 的项。相反,应该使用 setProperty 方法。如果在“有危险”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。
posted on 2008-01-10 04:40 Jeff Lau 阅读(1298) 评论(0)  编辑  收藏 所属分类: Jeff On Java 2008

只有注册用户登录后才能发表评论。


网站导航: