一.Properties 类基本定义:
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
一个属性列表可包含另一个属性列表作为它的“默认值”;如果未能在原有的属性列表中搜索到属性键,则搜索第二个属性列表。
因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。类似地,如果在“不安全”的 Properties 对象(即包含非 String 的键)上调用 propertyNames 或 list 方法,则该调用将失败。
二.常用方法:
①getProperty(String key)
用指定的键在此属性列表中搜索属性。
②load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。
③propertyNames()
返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键。
④setProperty(String key, String value)
调用 Hashtable 的方法 put。
三.java读取properties配置文件的几种方式
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
loadProperties1();
readProperty2();
readProperty3();
}
//方式一:基于InputStream读取配置文件:
private static void loadProperties1() throws IOException {
Properties properties = new Properties();
// FileInputStream stream = new FileInputStream("db.properties");
InputStream stream = PropertiesDemo.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(stream);
System.out.println(properties.getProperty("username"));
System.out.println(properties.getProperty("password"));
}
//方法二通过Spring中的PropertiesLoaderUtils工具类进行获取:
private static void readProperty2() {
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties("db.properties");
System.out.println(new String(properties.getProperty("username").getBytes("iso-8859-1"), "gbk"));
} catch (IOException e) {
e.printStackTrace();
}
}
//方法三通过 java.util.ResourceBundle 类读取:
private static void readProperty3() {
ResourceBundle resourceBundle = ResourceBundle.getBundle("db");
//遍历取值
Enumeration enumeration = resourceBundle.getKeys();
while (enumeration.hasMoreElements()) {
try {
String value = resourceBundle.getString((String) enumeration.nextElement());
System.out.println(new String(value.getBytes("iso-8859-1"), "gbk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}