Java学习-020-Properties 判断是否存在对应的 key 项

时间:2023-03-09 15:54:47
Java学习-020-Properties 判断是否存在对应的 key 项

在日常的脚本编写过程中,通常会判断配置文件中是否存在对应的配置项,以判断是否执行相应的业务逻辑。

小二上码。。。若有不足之处,敬请大神指正,不胜感激!

判断是否存在 key 项(配置项)的方法源码如下所示:

     /**
* Verify the key contains in properties or not
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium main.java.aaron.java.tools FileUtils.java propertiesKeyIsExist, 2014-11-20 16:31:10 Exp $
*
* @param prop : properties
* @param key : key
* @return boolean
*/
public boolean propertiesKeyIsExist(Properties prop, String key){
boolean success = false;
String item = ""; // verify the properties file is null
if (prop == null) {
this.message = "The content of properties file is null !";
this.logger.error(this.message); success = false;
return success;
} // verify the key is null
if ("".equals(key) || key == null) {
this.message = "There is no key {" + key + "} in properties config file.";
this.logger.error(this.message); success = false;
return success;
} // get keys from properties
Enumeration<?> enu = prop.propertyNames(); // verify the key is contains in properties or not
while (enu.hasMoreElements()) {
item = (String)enu.nextElement(); if (item.equals(key)) {
success = true;
}
} return success;
}

判断 properties 配置文件是否存在相应的配置项源码

测试源码如下所示:

     /**
* Test : Verify the key contains in properties file or not
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium test.java.aaron.java.tools FileUtilsTest.java test_propertiesKeyIsExist, 2014-11-20 16:35:15 Exp $
*
*/
public void test_propertiesKeyIsExist(){
this.message = "\n\n\nTEST:FileUtils.propertiesKeyIsExist(Properties prop, String key)";
this.logger.debug(this.message); this.fu = new FileUtils();
String filename = this.constantslist.PROJECTHOME + this.constantslist.FILESEPARATOR +
"testng-temp" + this.constantslist.FILESEPARATOR + "propertiesRead.properties"; Properties prop = this.fu.propertiesRead(filename); // print-1
prop.list(System.out); System.out.println("\n\n"); Assert.assertEquals(this.fu.propertiesKeyIsExist(prop, "host"), true, "Test case failed.");
}

测试源代码

至此, Java学习-020-Properties 判断是否存在对应的 key 项 顺利完结,希望此文能够给初学 Java 的您一份参考。

最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^