Convertire i file di Properties in Map e viceversa in Java
I file di properties, vengono molto utilizzati in ambito Java per memorizzare le configurazioni dei programmi; questo perchè sono abbastanza semplici da modificare.
In sostanza sono dei file composti da righe con KEY=VALUE.
In questo articolo (un pò vecchiotto, ma funzionante) abbiamo visto un esempio su come manipolarli.
Oggi vediamo come tradurre questi file in una Map e viceversa; e questo può essere molto utile.
Questi sono i due metodi:
public class PropsMap {
public Properties mapToProperties(Map<String, String> map) {
Properties prop = new Properties();
Set<Map.Entry<String, String>> set = map.entrySet();
set.stream().forEach((entry) -> {
prop.put(entry.getKey(), entry.getValue());
});
return prop;
}
public Map<String, String> propToMap(Properties prop) {
HashMap<String, String> hashMap = new HashMap<>();
Enumeration<Object> e = prop.keys();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
hashMap.put(s, prop.getProperty(s));
}
return hashMap;
}
}
Il primo converte una Map, passata come paremetro, in un Proerties.
Il secondo, fa l'esatto contrario; come parametro richiede un Properties.
Enjoy!
java map properties
Commentami!