2013-06-26 22 views
8

Questo nice article ci mostra come stampare tutte le proprietà correnti del sistema su STDOUT, ma ho bisogno di convertire tutto ciò che è in System.getProperties() in un HashMap<String,String>.Come convertire tutte le proprietà di sistema Java in HashMap <String, String>?

Quindi se v'è una proprietà di sistema chiamato "baconator", con un valore di "sì!", Che ho impostato con System.setProperty("baconator, "yes!"), allora voglio il HashMap di avere una chiave di baconator e un rispettivo valore di yes!, ecc Stessa idea per le proprietà di sistema all.

ho provato questo:

Properties systemProperties = System.getProperties(); 
for(String propertyName : systemProperties.keySet()) 
    ; 

Ma poi ottiene un errore:

Type mismatch: cannot convert from element type Object to String

Allora ho provato:

Properties systemProperties = System.getProperties(); 
for(String propertyName : (String)systemProperties.keySet()) 
    ; 

e sto ottenendo questo errore:

Can only iterate over an array or an instance of java.lang.Iterable

Qualche idea?

+0

Questo è un duplicato di http://stackoverflow.com/questions/17209260/converting-java-util-properties-to-hashmapstring-string –

risposta

7

ho fatto un test campione utilizzando Map.Entry

Properties systemProperties = System.getProperties(); 
for(Entry<Object, Object> x : systemProperties.entrySet()) { 
    System.out.println(x.getKey() + " " + x.getValue()); 
} 

Per il vostro caso, è possibile utilizzare questo per memorizzare nel vostro Map<String, String>:

Map<String, String> mapProperties = new HashMap<String, String>(); 
Properties systemProperties = System.getProperties(); 
for(Entry<Object, Object> x : systemProperties.entrySet()) { 
    mapProperties.put((String)x.getKey(), (String)x.getValue()); 
} 

for(Entry<String, String> x : mapProperties.entrySet()) { 
    System.out.println(x.getKey() + " " + x.getValue()); 
} 
2

loop sul Set<String> (che è Iterable) che viene restituito dal metodo stringPropertyNames(). Durante l'elaborazione di ciascun nome di proprietà, utilizzare getProperty per ottenere il valore della proprietà. Quindi hai le informazioni necessarie per put i tuoi valori di proprietà nel tuo HashMap.

0

Questo funziona

Properties properties= System.getProperties(); 
for (Object key : properties.keySet()) { 
    Object value= properties.get(key); 

    String stringKey= (String)key; 
    String stringValue= (String)value; 

    //just put it in a map: map.put(stringKey, stringValue); 
    System.out.println(stringKey + " " + stringValue); 
} 
0

entrambi i casi è possibile utilizzare il metodo entrySet() da Properties per ottenere un tipo di Entry da Properties che è Iterable o si potrebbe utilizzare il metodo stringPropertyNames() dalla classe Properties per ottenere un Set di chiavi in questa lista di proprietà. Utilizzare il metodo getProperty per ottenere il valore della proprietà.

Problemi correlati