Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing map in properties file

I know that I can build a Map as below.

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

I'd like to store the values of my map in a config file. I'm already storing the values for a different hashset in the config file by doing values=value1,value2,value3 and then
new HashSet<String>(Arrays.asList(prop.getProperty(values).split(",")))

I'd like to do something similar for my map. Any tips? I'm using java.util.Properties

like image 454
Lemonio Avatar asked Jul 26 '13 18:07

Lemonio


People also ask

How do we store data into properties file?

Creating a .properties file − Instantiate the Properties class. Populate the created Properties object using the put() method. Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.

What is the difference between MAP and Properties?

A map is meant for normal key-value pair usage in code. Properties are typically used for storing and loading configuration values from a file.

Which annotation is used to map with properties file?

Learn to use the Spring @Value annotation to configure fields from property files, system properties, etc.


1 Answers

Since you've indicated you don't want to use JSON, you could store the map as a single property like this:

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

Use Guava's Splitter and Joiner to simplify reading and writing the map:

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 so long as the keys and values do not contain "," or "=" characters.

like image 193
dnault Avatar answered Sep 20 '22 16:09

dnault