Java Properties,读取使用¶
Java 读写Properties配置文件
Properties类与Properties配置文件¶
Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。
Properties 类被许多Java类使用。例如,在获取环境变量时它就作为System.getProperties()
方法的返回值。
Properties中的主要方法¶
load(InputStream inStream)¶
这个方法可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象。如下面的代码:
// 读取属性文件a.properties
InputStream in = new BufferedInputStream(new FileInputStream("a.properties"));
prop.load(in); // 加载属性列表
for (String key : prop.stringPropertyNames()) {
System.out.println(key + ":" + prop.getProperty(key));
}
in.close();
store(OutputStream out, String comments)¶
这个方法将Properties类对象的属性列表保存到输出流中。如下面的代码:
// 保存属性到b.properties文件
FileOutputStream bFile = new FileOutputStream("b.properties", true); // true表示追加打开
prop.setProperty("phone", "10086");
prop.store(bFile, "The New properties file\nWritten by Rust");
bFile.close();
comments 表示注释信息;注释信息后面是属性文件的当前保存时间信息。
getProperty/setProperty¶
这两个方法是分别是获取和设置属性信息。
public static void main(String[] args) {
Properties prop = new Properties();
try {
// 读取属性文件a.properties
InputStream in = new BufferedInputStream(new FileInputStream("a.properties"));
prop.load(in); // 加载属性列表
for (String key : prop.stringPropertyNames()) {
System.out.println(key + ":" + prop.getProperty(key));
}
in.close();
// 保存属性到b.properties文件
FileOutputStream bFile = new FileOutputStream("b.properties", true);//true表示追加打开
prop.setProperty("phone", "10086");
prop.store(bFile, "The New properties file\nWritten by Rust");
bFile.close();
FileOutputStream cFile = new FileOutputStream("c.properties", false);
prop.store(cFile, null);
cFile.close();
} catch (Exception e) {
System.out.println(e);
}
}
运行结果如下
a.properties
name=root
pass=liu
key=value
b.properties
#The New properties file
#Written by Rust
#Thu May 23 22:34:36 GMT+08:00 2019
phone=10086
name=root
key=value
pass=liu
c.properties
#Thu May 23 22:34:36 GMT+08:00 2019
phone=10086
name=root
key=value
pass=liu