zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java遍历Properties所有元素的方法实例

JAVA实例遍历方法 所有 元素 properties
2023-06-13 09:15:12 时间

复制代码代码如下:


 //初始化properties

Propertiespro=newProperties();

try{
   InputStreaminStr=ClassLoader.getSystemResourceAsStream("wahaha.properties");
   pro.load(inStr);
}catch(FileNotFoundExceptione){
   e.printStackTrace();
}catch(IOExceptione){
   e.printStackTrace();
}
 


propertyNames()返回属性列表中所有键的枚举

 

复制代码代码如下:

Enumerationenu2=pro.propertyNames();
while(enu2.hasMoreElements()){
   Stringkey=(String)enu2.nextElement();
   System.out.println(key);
}
 

 返回所有的属性值

 

复制代码代码如下:
 //Properties继承于Hashtable,elements()是Hashtable的方法,返回哈希表中的值的枚举。
Enumerationenu=pro.elements();
while(enu.hasMoreElements()){
   Stringkey=(String)enu.nextElement();
   System.out.println(key);
}
 

 返回所有的属性(属性名,属性值)

 

复制代码代码如下:
 //Properties继承于Hashtable,entrySet()是Hashtable的方法,
//返回此Hashtable中所包含的键的Set视图。此collection中每个元素都是一个Map.Entry
Iteratorit=pro.entrySet().iterator();
while(it.hasNext()){
   Map.Entryentry=(Map.Entry)it.next();
   Objectkey=entry.getKey();
   Objectvalue=entry.getValue();
   System.out.println(key+":"+value);
}
 

 假设wahaha.properties中内容为:
------------------------------
name1=xxxx
name2=yyyyy
name3=zzzzzzz
------------------------------

上面的代码将会输出:
--------------------------
name1
name2
name3
xxxx
yyyyy
zzzzzzz
name1:xxxx
name2:yyyyy
name3:zzzzzzz
---------------------------------