2011-10-11 109 views
1

回答 我只是找到了我一直在尋找:Java屬性的HashMap閱讀

Properties properties = new Properties(); 
FileInputStream in = new FileInputStream("/somePath/file.map"); 
properties.load(in); 
in.close(); 
HashMap<String, String> propMap = new HashMap<String, String>((Map) properties); 

這讓我有出去需要知道的屬性名稱獲取打開的屬性數據回到HashMap中。

原始問題。

我有下面的代碼寫出一個HashMap的結果。我想知道最簡單的方法來打開這個屬性備份並將數據放回到HashMap中,putAll是將數據存入屬性並存儲數據的好方法。我沒有看到getAll檢索它,並且在創建hashmap之前HashMap鍵/值數據未知,因此不能僅通過屬性名稱進行檢索。創建後的數據將是靜態的,因此我可以物理地打開基於散列表寫入的文件以獲取屬性名稱,但不必這樣做。謝謝你的幫助。

Properties properties = new Properties(); 
properties.putAll(mapTabSets); 
properties.store(new FileOutputStream("/somePath/file.map"),"Java properties); 

回答

2

雖然性能沒有GETALL功能,他們確實有

propertynames() 
stringPropertyNames() 

兩者將提供屬性的所有鍵的集合。然後,您可以遍歷集合,並通過

properties.getProperty(String) 
+0

謝謝..這兩個答案都幫助了我很多,但我使用propertynames()來獲取密鑰作爲集合,因此請檢查它,但都得到了答案。 – Green

1

請嘗試以下操作。

Properties properties = new Properties(); 
properties.load(new FileInputStream("/somePath/file.map")); 
+0

由於提取屬性的所有值,我沒有打開屬性文件有問題,只是不知道如何得到它放回我的HashMap中,但我想通了,並添加了對我的問題的評論。 – Green

+0

有一點需要注意的是,屬性是一個Hashtable的實現,它在技術上是一個Map(具有鍵值對)。祝你好運。 – tjg184

+0

這幫了很大忙。謝謝..如果我明白我在讀什麼,它們在獲取數據方面似乎有點不同,就像在for循環中一樣,但這樣做的確幫助我更好地理解它。 – Green

-1
package com.mkyong.common; 

    import java.io.IOException; 
    import java.util.HashMap; 
    import java.util.Properties; 

    public class ClassName { 

     private static HashMap<String, String> mymap = new HashMap<String, String>(); 

     public ClassName() throws IOException{ 
      Properties prop = new Properties(); 
      prop.load(ClassName.class.getClassLoader().getResourceAsStream("ini.properties")); 

      mymap.put("1", prop.getProperty("required.firstName")); 
      mymap.put("2", prop.getProperty("required.lastName")); 
      mymap.put("3", prop.getProperty("equired.address")); 
     } 

     public static void main(String[] args) throws IOException { 
      ClassName className = new ClassName(); 
      System.out.println("The Value of Key-1 ::" + mymap.get("1")); 
     } 
    } 

Use the properties file:- 
**************************** 
required.firstName=Nitesh 
required.lastName=Rathore 
required.address=DangeChowk