Properties类
在一个系统中需要一些配置信息,那么如何更好地管理这些配置(增删改查)?Properties为我们提供了这样的基本功能,Properties用简单的key、value存储系统的配置信息。
Properties类的使用
下面的这张图展示一个简单的系统如何在自己的运行器使用Properties管理自己的配置信息。
启动
在系统启动的时候,会发生图上前三个步骤。首先,程序从从一个位置加载一个Poeperties,然后再根据Properties里面的值来初始化整个系统(例如根据数据源的配置文件,连接数据源)。运行
在运行期间,可能修改一些配置信息,如果希望这个更改在未来系统中也会生效,那么就需要将修改信息存储在文件里面。退出
为了保证下次启动的时候是当前的配置信息,需要进行save一下当前的配置信息。
例子
下面我们来举例说明如何使用Properties。
@Test
public void testStore(){
Properties properties=new Properties();
OutputStream outputStream=null;
try {
outputStream=new FileOutputStream("config.properties",false);
properties.setProperty("name","yeming");
properties.setProperty("age","11");
properties.store(outputStream,"yeming config properties");
}catch (IOException e){
e.printStackTrace();
}
finally {
if(outputStream!=null){
try{
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
在上面的测试用例中,我们首先定义了Properties,然后设置了Properties的值,最后将当前Properties的信息存放在文件中。
接下来我们测试Properties的load():
@Test
public void testLoad() {
Properties properties = new Properties();
InputStream inputStream = null;
try {
inputStream = new FileInputStream("config.properties");
properties.load(inputStream);
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我们在上面的代码中首先定义了Properties实例,然后我们从配置文件中读取配置信息,然后打印出来所有的配置项以及配置内容。
最后我们可以看一下如何获取系统属性,通过System.getProperties(),我们可以获取jvm的一些信息,例如jdk的运行版本等信息。
实现原理
我们已经知道了如何使用Properties,那么Properties的实现原理是什么呢?
Properties继承的是HashTable,当setProperties的时候,利用的是HashTable的put进行存储。当我们store配置信息到文件中的时候,直接将内存中的key、value全部存储到文件中。