Saving a map in a properties file

I know that I can create a map as shown below.

private static final ImmutableMap<String,String> WordMap = ImmutableMap.<String, String>builder() .put("blah", "blahblah").put("blabla", "blahblahblah").build() 

I would like to save the values โ€‹โ€‹of my map in a configuration file. I already store the values โ€‹โ€‹for another hash set in the configuration file, doing values=value1,value2,value3 , and then new HashSet<String>(Arrays.asList(prop.getProperty(values).split(",")))

I would like to do something similar for my card. Any tips? I am using java.util.Properties

+8
java hashmap properties map config
source share
3 answers

Since you indicated that you do not want to use JSON, you can save the map as one property like this:

 map=key1=value1,key2=value2,key3=value3 

Use Guava Splitter and Joiner to make reading and writing a map easier:

 String formatMap(Map<String, String> map) { return Joiner.on(",").withKeyValueSeparator("=").join(map); } Map<String, String> parseMap(String formattedMap) { return Splitter.on(",").withKeyValueSeparator("=").split(formattedMap); } 

This will work until the keys and values โ€‹โ€‹contain the characters "," or "=".

+17
source share

Format the contents of the map as a string. Use a standard format like JSON. In the json-smart library, this would look like this:

 JSONObject json = new JSONObject(); json.putAll(WordMap); String serializedMap = json.toString(); prop.setProperty("wordMap", serializedMap); 

To analyze a map:

 String serializedMap = prop.getProperty("wordMap"); JSONObject json = (JSONObject) JSONValue.parse(serializedMap); Map<String, String> wordMap = new HashMap<>(); for (Map.Entry<String,Object> entry : json.entrySet()) { wordMap.put(entry.getKey(), (String) entry.getValue()); } 
+2
source share

java.util.Properties internally uses a hash table to store the pairs of values โ€‹โ€‹mentioned in the properties file. You can fully use it for your purpose.

+1
source share

All Articles