Properties类:
Public class properties extends HashTable
可见Properties类继承了HashTable,而HashTable又实现了Map接口,所以可对properties对象应用put和putAll方法。但不建议使用这两个方法,因为他们允许调用者插入其键或值不是String的项。相反,应该使用setProperty方法。如果在“不安全”的properties对象(即包含非String的键或值)上调用store或save方法,则该调用将失败。
Properties的常用方法:
1.setProperty(String key,String value)
调用HashTable的方法put。
2.getProperty(String key)
用指定的键在此属性列表中搜索属性
3.getProperty(String key, String defaultValue)
用指定的键在属性列表中搜索属性。
4.load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。
5.load(Reader reader)
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
6.loadFromXML(InputStream in)
将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。
7.store(OutputStream out, String comments)
以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。
8.store(Writer writer, String comments)
以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
9.storeToXML(OutputStream os, String comment)
发出一个表示此表中包含的所有属性的 XML 文档。
10.storeToXML(OutputStream os, String comment, String encoding)
使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。
11.clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
使用J2SE API读取Properties文件的六种方法:
(1)使用java.util.Properties类的load()方法
示例:
InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
(2)使用java.util.ResourceBundle类的getBundle()方法
示例:
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
(3)使用java.util.PropertyResourceBundle类的构造函数
示例:
InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
(4)使用class变量的getResourceAsStream()方法
示例:
InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
(5)使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例:
InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
(6)使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例:
InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);